簡體   English   中英

c#無法訪問文件,因為它正被另一個進程使用

[英]c# Cannot access file because it is being used by another process

我正在嘗試在創建文件后寫入文件。 它無法訪問它,這是我的代碼:

                string[] name = file.Split('.');
                HttpWebRequest FileRequest = (HttpWebRequest)WebRequest.Create(URL + name[0] + ".html");
                FileRequest.UserAgent = "FSL File Getter Agent";

                using (HttpWebResponse response = (HttpWebResponse)FileRequest.GetResponse())
                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    File.Create("C:\\Users\\" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\')[1] + "\\FSL\\" + Item + "\\" + file);
                    File.WriteAllText("C:\\Users\\" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\')[1] + "\\FSL\\" + Item + "\\" + file, reader.ReadToEnd());
                }

這是堆棧跟蹤:

The process cannot access the file 'C:\Users\Winksplorer\FSL\TestPRG\main.py' because it is being used by another process.
Stack Trace:
   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.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
   at System.IO.File.InternalWriteAllText(String path, String contents, Encoding encoding, Boolean checkHost)
   at System.IO.File.WriteAllText(String path, String contents)
   at FSL.Program.GetPKG(String URL, String Item) in Z:\FSL\Program.cs:line 85
   at FSL.Program.Main(String[] args) in Z:\FSL\Program.cs:line 30

File.Create返回一個您很樂意忽略的FileStream 此操作的結果是持有打開文件的句柄,該句柄不會被及時處理。 此外,您然后嘗試使用另一種方法File.WriteAllText使用不同的文件句柄寫入該文件,這會導致您看到的錯誤。

解決此問題的方法是使用您最初創建的FileStream ,但更好的是,只需使用其中一個流CopyTo方法

using var stream = response.GetResponseStream();
using var fs = File.Create(...)
stream.CopyTo(fs);

免責聲明:這些方法有異步版本,還有許多其他方法可以實現相同的目的。 這沒有經過測試,可能有印刷錯誤,可能包含也可能不包含堅果的痕跡,並不意味着成為完美代碼的堡壘......它只是一個致敬......簡而言之,研究你使用的方法互聯網

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM