Cant Access File because it is being used by another process

前端 未结 6 2134
我寻月下人不归
我寻月下人不归 2020-12-11 09:25

I have an ASP.NET program where i am downloading a file from web using DownloadFile method of webClient Class and the do some modifications on it. then i am Saving it to ano

相关标签:
6条回答
  • 2020-12-11 10:08

    Generally, I think your code should looking something like this.

    WebClient wc = new WebClient();
    wc.DownloadFile("http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png", "Foo.png");
    FileStream fooStream;
    using (fooStream = new FileStream("foo.png", FileMode.Open))
    {
        // do stuff
    }
    File.Move("foo.png", "foo2.png");
    
    0 讨论(0)
  • 2020-12-11 10:10

    Are you explicitly closing the file stream after you make your changes?

    0 讨论(0)
  • 2020-12-11 10:19

    I've had very good success using the tools from SysInternals to track which applications are accessing files and causing this kind of issue.

    Process Monitor is the tool you want - set it up to filter the output to just files in the folder you're interested in, and you'll be able to see every access to the file.

    Saves having to guess what the problem is.

    0 讨论(0)
  • 2020-12-11 10:19

    try the following, set your filestream to Asynchronus mode (3rd parameter)

    FileStream myStream = File.Create(fileName, results.Length,FileOptions.Asynchronous);
    //make sure you close the file
    myStream.Write(results, 0, results.Length);
    myStream.Flush();
    myStream.Close();
    myStream.Dispose();
    

    if this fails reset the attributed of the file b4 you access it

    File.SetAttributes(Server.MapPath(sendFilepath), FileAttributes.Normal);
    
    0 讨论(0)
  • 2020-12-11 10:24

    I dont know if this will solve your problem..

    I got the exact same error when writing to a text file and then trying to open it afterwards.

    It was solved by flushing the writer and then closing it after writing to the file..

    0 讨论(0)
  • 2020-12-11 10:25

    this may help....sorry its VB not C but hey...

    This works

        Dim fs As FileStream = Nothing
        fs = File.Create("H:\test.txt")
        fs.Close()
        File.Delete("H:\test.txt")
    

    This doesn't, give "file being used by another process" error

        File.Create("H:\test.txt")
        File.Delete("H:\test.txt")
    
    0 讨论(0)
提交回复
热议问题