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