为什么我得到IOException:进程无法访问该文件?

时间:2014-03-25 07:32:00

标签: 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
    {
        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: 

为什么我会收到异常,我该如何解决?

1 个答案:

答案 0 :(得分:1)

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

finally
{
    sourceStream.Close();
    requestStream.Close();
    response.Close();
}

这种方式即使您有例外,一切都将被关闭。

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

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

类似的东西:

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

我希望这会有所帮助