繁体   English   中英

Windows C#中找不到文件异常

[英]File not found exception in Windows C#

第一次打开文件,读取文件内容并保存时,应用程序运行良好。 但是,当我再次打开同一文件时,出现了一个文件未找到的异常 如何刷新流?

FileStream usrFs = null;
try
{
    usrFs = new FileStream(xmlSource, FileMode.Open, FileAccess.Read,
    FileShare.ReadWrite);
}
catch (IOException)
{
    MessageBox.Show("File not found in the specified path");
}

XML

<?xml version="1.0"?>
<MenuItem BasePath="c:\SampleApplication">

堆栈跟踪

at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)    
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)    
at SampleApplication.MainForm.ProcessDocument(BackgroundWorker worker, DoWorkEventArgs e) in C:\Users\273714\Desktop\CRAFTLite - VSTS\SampleApplication\MainForm.cs:line 179

您可以尝试以下方法:

    using (FileStream usrFs = new FileStream(xmlSource, FileMode.Open, 
      FileAccess.Read, FileShare.ReadWrite) 
     {
       ... 
     }

读取文件后,完成读取或写入后, close filestream ...

finally
{
   fileStream.Close();
}

IOEXCEPTIONS将具有不同的类型,并且您只是在显示未找到文件的消息。 在您的情况下, 找不到文件将不会出现异常...它将是file already open by another process

您将收到IOException ,这可能是由许多问题引起的。 如果要检查找不到文件,则应检查System.IO.FileNotFoundException 没有任何其他信息,很难准确地说明导致问题的原因。

一个问题是当前您没有关闭文件流。 您需要在finally方法中调用usrFs.Close() 更好的方法是使用using关键字以确保文件已关闭。

using( var usrFs = new FileStream(xmlSource, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) )
{
    // do things here
}
// usrFs is closed here, regardless of any exceptions.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM