C# 为什么我';m获取IOException:进程无法访问该文件?

C# 为什么我';m获取IOException:进程无法访问该文件?,c#,streamreader,ioexception,C#,Streamreader,Ioexception,代码如下: static string ftpurl = "ftp://ftp.test.com/files/theme/"; static string filename = @"c:\temp\test.txt"; static string ftpusername = "un"; static string ftppassword = "ps"; static string value; public static void test() { try {

代码如下:

static string ftpurl = "ftp://ftp.test.com/files/theme/";
static string filename = @"c:\temp\test.txt";
static string ftpusername = "un";
static string ftppassword = "ps";
static string value;

public static void test()
{
    try
    {
        FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(
        ftpurl + "/" + Path.GetFileName(filename));
        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Credentials = new NetworkCredential(ftpusername, ftppassword);

        StreamReader sourceStream = new StreamReader(@"c:\temp\test.txt");
        byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

        response.Close();
    }
    catch(Exception err)
    {
        string t = err.ToString();
    }
}
例外情况如下:

StreamReader sourceStream = new StreamReader(@"c:\temp\test.txt");
例外情况如下:

The process cannot access the file 'c:\temp\test.txt' because it is being used by another process

System.IO.IOException was caught
  HResult=-2147024864
  Message=The process cannot access the file 'c:\temp\test.txt' because it is being used by another process.
  Source=mscorlib
  StackTrace:
       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, Boolean checkHost)
       at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
       at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
       at System.IO.StreamReader..ctor(String path)
       at ScrollLabelTest.FtpFileUploader.test() in e:\scrolllabel\ScrollLabel\ScrollLabel\FtpFileUploader.cs:line 33
  InnerException: 

为什么会出现异常以及如何修复它?

您应该使用finally块,并关闭那里的所有流:

finally
{
    sourceStream.Close();
    requestStream.Close();
    response.Close();
}
这样即使你有一个例外,一切都会被关闭

发生这种情况的原因可能是,在关闭该文件之前,您遇到了异常,然后,当您再次运行程序并尝试打开时,该文件仍然打开

首先关闭文件,然后使用finally块或
using
语句

比如:

using (StreamReader reader = new StreamReader("file.txt"))
{
    line = reader.ReadLine();
}

我希望这有助于

如果该文件在记事本中打开,请将其关闭。或者如果有其他程序启动实例,请将其杀死。您是否考虑过该文件被其他进程使用的可能性?(或者问题是您不知道如何找到其他流程?)