2014-03-25 45 views
0

這是代碼:爲什麼我得到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: 

爲什麼我得到異常以及如何我修復它?

+5

如果該文件是在記事本中打開,關閉它。 –

+3

或者如果有程序啓動的另一個實例,請殺死它。 – Raptor

+1

您是否考慮過該文件正在被另一個進程使用的可能性? (或者是你不知道如何找到其他過程的問題?) –

回答

1

您應該使用finally塊,並關閉所有流有:

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

這樣,即使你有一個例外,一切都將被關閉。

這happends因爲也許你已經得到該文件結束前的異常,然後,當你再次運行程序,並嘗試打開,仍然打開。

先關閉您的文件,然後使用finally塊,或using聲明。

喜歡的東西:

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

我希望這有助於

相關問題