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:
爲什麼我得到異常以及如何我修復它?
如果該文件是在記事本中打開,關閉它。 –
或者如果有程序啓動的另一個實例,請殺死它。 – Raptor
您是否考慮過該文件正在被另一個進程使用的可能性? (或者是你不知道如何找到其他過程的問題?) –