简体   繁体   中英

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

I am Trying To Write To A File After Creating It. And It Cannot access it, this is my code:

                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());
                }

This Is The Stack Trace:

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 a FileStream for which you are happily ignoring. The result of this action is holding a handle to the file open which will not get disposed in a timely manner. Furthermore, you are then trying to use another method File.WriteAllText to write to that file using a different file handle which results in the error you see.

The solve to this is to use the FileStream you originally created, however even better, just use one of the streams CopyTo Methods

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

Disclaimer : There are async versions to these methods and many other ways to achieve the same thing. This wasn't tested, may have typographic errors, may or may not contain traces of nuts, and was not meant to be the bastion of perfect code... Its only a tribute... In short, research the methods you use from the interwebs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM