C# 如何获取StreamWriter的完整路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10483314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get full path of StreamWriter
提问by javapowered
I'm creating a StreamWriterusing a relative path. But the file doesn't appear. To troubleshoot, I want to check that the full path is what I'm expecting. So having a StreamWriterinstance, how can I get the full path of the file it's going to write to?
我正在StreamWriter使用相对路径创建一个。但是文件没有出现。要进行故障排除,我想检查完整路径是否符合我的预期。那么有一个StreamWriter实例,我怎样才能获得它要写入的文件的完整路径?
string fileName = "relative/path.txt"
StreamWriter sw= new StreamWriter(fileName);
// What is the full path of 'sw'?
采纳答案by Steve
To get the full path from a relative path, use the Path.GetFullPathmethod.
要从相对路径获取完整路径,请使用Path.GetFullPath方法。
For example:
例如:
string fileName = "relative/path.txt";
string fullPath = Path.GetFullPath(fileName);
回答by RajN
Might be the directory 'relative' not exists. Either create it manually. Or create it programmatically as below
可能是目录“相对”不存在。要么手动创建。或以编程方式创建它,如下所示
string fileName = @"relative\path.txt";
fileName = Path.GetFullPath(fileName);
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
StreamWriter sw= new StreamWriter(fileName, true);
回答by Jeppe Stig Nielsen
In my version of the framework, this seems to work:
在我的框架版本中,这似乎有效:
string fullPath = ((FileStream)(streamWriter.BaseStream)).Name;
(Found by debugging.)
(通过调试找到。)
回答by Serj-Tm
var fstream = sw.BaseStream as System.IO.FileStream;
if (fstream != null)
Console.WriteLine(GetAbsolutePathByHandle(fstream.SafeFileHandle));
[DllImport("ntdll.dll", CharSet = CharSet.Auto)]
private static extern int NtQueryObject(SafeFileHandle handle, int objectInformationClass, IntPtr buffer, int StructSize, out int returnLength);
static string GetAbsolutePathByHandle(SafeFileHandle handle)
{
var size = 1024;
var buffer = Marshal.AllocCoTaskMem(size);
try
{
int retSize;
var res = NtQueryObject(handle, 1, buffer, size, out retSize);
if (res == -1073741820)
{
Marshal.FreeCoTaskMem(buffer);
size = retSize;
Marshal.AllocCoTaskMem(size);
res = NtQueryObject(handle, 1, buffer, size, out retSize);
}
if (res != 0)
throw new Exception(res.ToString());
var builder = new StringBuilder();
for (int i = 4 + (Environment.Is64BitProcess ? 12 : 4); i < retSize - 2; i += 2)
{
builder.Append((char)Marshal.ReadInt16(buffer, i));
}
return builder.ToString();
}
finally
{
Marshal.FreeCoTaskMem(buffer);
}
}
Output:
输出:
\Device\HarddiskVolume2\bla-bla\relative\path.txt
回答by Aave
Dim fs As FileStream = CType(sw.BaseStream, FileStream)
Dim fi As New FileInfo(fs.Name)
Console.WriteLine(fi.FullName)

