FileStream.close () does not free the file for other processes

I have the following code in the page_Load function. When the page loads for the first time after starting Visual Studio, everything works fine.
But any other call to open a file after that returns IOException: "File is in use by another process"even when a file is opened directly in VisualStudio Solution, this error is returned (of course, not as an exception)

FileStream mailinglist_FileStream = new FileStream(@"\foobarFile.txt", FileMode.Open);
PeekingStreamReader mailinglist_Reader = new PeekingStreamReader(mailinglist_FileStream);
//Do some stuff with the file
mailinglist_FileStream.Close();
mailinglist_Reader.Close();
mailinglist_Reader.Dispose();
mailinglist_FileStream.Dispose();

Why is the file still locked? and why does Visual Studio completely restart the reset file? when checking file properties, he says:

Build action: Content
Copy to output directory: do not copy

I am only reading this file. can i do something similar adLockOptimisticso that multiple processes can access the file?

+5
3

? Visual Studio reset ? - [...] , : , - , , /.

, Visual Studio [...] ": IIS Express ASP.NET Dev Server, IDE, , , .

, ? [...] " , , .

, , using , IDisposable :

// FileShare.ReadWrite will allow other processes 
// to read and write the target file even if other processes 
// are working with the same file
using (FileStream mailinglist_FileStream = new FileStream(@"\foobarFile.txt", FileMode.Open, FileShare.ReadWrite))
using (PeekingStreamReader mailinglist_Reader = new PeekingStreamReader(mailinglist_FileStream))
{
      // Do your stuff. Using blocks will call Dispose() for 
      // you even if something goes wrong, as it equal to a try/finally! 
      // Also check how using statements can be chained without extra { }           
 }

. - adLockOptimistic, ?

, File.Open FileShare :

+7

using:

using (FileStream fileStream = File.Open(@"C:\somefile", FileMode.Open, FileAccess.Read))
{
    ...
}

using , , , .

, - . , , using.

+1

Try using blocks using, this may not fix the lock problem, but it is better for disposable objects.

using (FileStream mailinglist_FileStream = new FileStream(@"\foobarFile.txt", FileMode.Open))
{
    using (PeekingStreamReader mailinglist_Reader = new PeekingStreamReader(mailinglist_FileStream))
    {
        ...            
    }
}

Also, try closing mailinglist_Readerup mailinglist_FileStream.

0
source

All Articles