我正在StreamWriter
使用相对路径创建一个。但是文件没有出现。要进行故障排除,我想检查完整路径是否符合我的预期。所以有一个StreamWriter
实例,我怎样才能得到它要写入的文件的完整路径?
string fileName = "relative/path.txt"
StreamWriter sw= new StreamWriter(fileName);
// What is the full path of 'sw'?
我正在StreamWriter
使用相对路径创建一个。但是文件没有出现。要进行故障排除,我想检查完整路径是否符合我的预期。所以有一个StreamWriter
实例,我怎样才能得到它要写入的文件的完整路径?
string fileName = "relative/path.txt"
StreamWriter sw= new StreamWriter(fileName);
// What is the full path of 'sw'?
在我的框架版本中,这似乎有效:
string fullPath = ((FileStream)(streamWriter.BaseStream)).Name;
(通过调试发现。)
要从相对路径获取完整路径,请使用Path.GetFullPath方法。
例如:
string fileName = "relative/path.txt";
string fullPath = Path.GetFullPath(fileName);
可能是“相对”目录不存在。要么手动创建它。或以编程方式创建它,如下所示
string fileName = @"relative\path.txt";
fileName = Path.GetFullPath(fileName);
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
StreamWriter sw= new StreamWriter(fileName, true);
使用可空类型和安全转换(as
不抛出异常):
_logger.LogInformation("Wrote file at {0}", (streamWriter.BaseStream as FileStream)?.Name);
?
仅当左侧表达式的结果不是时才访问该属性null
,否则返回(计算为)null
(就像它等价于E is T ? (T)(E) : (T)null
)。
如果你愿意,你可以像这样检查演员阵容null
:
var fs = streamWriter.BaseStream as FileStream;
if (fs != null)
{
_logger.LogInformation("Wrote file at {0}", fs.Name);
}
但这比您需要的代码更多。用 C# 7+ 编写上述示例的更现代的方法是使用is
运算符:
if (streamWriter.BaseStream is FileStream fs)
{
_logger.LogInformation("Wrote report file at {0}", fs.Name);
}
这具有额外的好处,即如果无法执行强制转换,则根本不会发生日志调用,因为实际上fs
在null
使用is
. 整个is
表达式的计算结果为真或假,但从不null
。
作为对@Jeppe Stiehl Nielsen 回复的评论,这会更好,但我不能添加评论:在 VB.Net 中,这变成:
Dim fullPath As String = CType(streamWriter.BaseStream, FileStream).Name
我不确定为什么CType
需要它,并且仅用于此属性,而所有其他属性都不需要,但它是必需的。
Dim fs As FileStream = CType(sw.BaseStream, FileStream)
Dim fi As New FileInfo(fs.Name)
Console.WriteLine(fi.FullName)
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);
}
}
输出:
\Device\HarddiskVolume2\bla-bla\relative\path.txt