繁体   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