我想知道如何从IOException消息中提取文件路径。
下面的代码搜索C:\Temp下的子目录并检测是否正在打开任何*_test.xlsx:
class Program
{
static void Main(string[] args)
{
string[] files = Directory.GetFiles(@"C:\Temp", "*_test.xlsx", SearchOption.AllDirectories);
try
{
if (files == null)
{
Console.WriteLine("File Not Found");
}
else
{
foreach (var file in files)
{
using (Stream stream = new FileStream(file, FileMode.Open))
{
// Do Nothing
}
}
}
}
catch (IOException ex)
{
Console.WriteLine(ex); // Here I'd like to show only the 'C:\Temp\3_folder\3_test.xlsx' part
}
}
}如果文件正在打开,则捕获一个IOException并显示:
System.IO.IOException: The process cannot access the file 'C:\Temp\3_folder\3_test.xlsx' because it is being used by another process.
at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.FileStream..ctor(String path, FileMode mode)
at CheckIfFileInUse.Program.Main(String[] args) in C:\Users\xxxxx\source\repos\CheckIfFileInUse\Program.cs:line 22然而,我不需要完整的信息。
我只需要文件路径(在本例中是C:\Temp\3_folder\3_test.xlsx)。
我搜索并找到了this answer,但这不是我想要的。
frame.GetFileName() of StackTrace()返回程序文件路径(在我的例子中是C:\Users\xxxxx\source\repos\CheckIfFileInUse\Program.cs)。
如何从IOException消息中提取文件路径?
发布于 2021-08-30 06:55:09
一般情况下,您不能这样做,因为并非每个IOException都有一个与其关联的文件名。也许EndOfStreamException (即IOException)对不需要文件的MemoryStream进行操作。
但你自己来做这件事是件小事。在内部级别捕获异常,然后抛出自己的异常。注意<--在哪里进行更改
class Program
{
static void Main(string[] args)
{
string[] files = Directory.GetFiles(@"C:\Temp", "*_test.xlsx", SearchOption.AllDirectories);
try
{
if (files == null)
{
Console.WriteLine("File Not Found");
}
else
{
foreach (var file in files)
{
try // <--
{
using (Stream stream = new FileStream(file, FileMode.Open))
{
// Do Nothing
}
}
catch (IOException ex) // <--
{
var fileex = new IOExceptionWithFileInfo(file);
fileex.InnerException = ex; // Keep the original information
throw fileex;
}
}
}
}
catch (IOExceptionWithFileInfo ex) // <--
{
Console.WriteLine(ex.FileName);
}
}
}TODO作为练习:实现从IOExceptionWithFileInfo派生的类Exception。
捕获内部级别还可以帮助您处理所有文件,并生成所有有问题的文件的列表,如下所示:
var listOfErrors = new List<IOExceptionWithFileInfo>();
[...]
catch (IOException ex)
{
var fileex = new IOExceptionWithFileInfo(file);
fileex.InnerException = ex; // Keep the original information
listOfErrors.Add(fileex);
}
[...]
if (listOfErrors.Length > 0)
{
// Display all of them to the user
}https://stackoverflow.com/questions/68979906
复制相似问题