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 returns 一个 FileStream 你很高兴地忽略了。此操作的结果是持有打开文件的句柄,不会及时处理。此外,您然后尝试使用另一种方法 File.WriteAllText 使用不同的文件句柄写入该文件,这会导致您看到错误。

解决这个问题的方法是使用您最初创建的 FileStream,但更好的是,只需使用其中一种流 CopyTo 方法

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

免责声明:这些方法有异步版本,还有许多其他方法可以实现相同的目的。这没有经过测试,并不意味着成为完美代码的堡垒。只是致敬而已。。。总之,研究你使用的方法