Used FileStream

If my file stream is used (every time I try to debug it gets on the first line and says it is used), how can I force the release? every time it gets into this code, I get a message that something is using it:

FileStream fileStream = File.Open(@"C:\somefile", FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[fileStream.Length];
...etc.
fileStream.Close();
+3
source share
4 answers

Learn to use using:

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

The design usingensures that the file is closed when you leave the block, even if an exception is thrown.

Your problem may not be here, but somewhere else in your code. You will need to go through all your code and look for the places where you opened the files, but do not put them in a statement using.

+17

File.ReadAllText(string path);

File.ReadAllBytes(string path);

, .

+4

using ; . "" .

( using ) - , FileStream.Close , . , . , , Close finally.

, , try/catch/finally try/using/catch. , finally, - , IDisposable, . :

try {
    using (DisposableObject obj1 = GetDisposableObject()) {
        // do something

        using (DisposableObject obj2 = GetAnotherDisposableObject()) {
            // do something else

            using (DisposableObject obj3 = GetYetAnotherDisposableObject()) {
                // do even more things

                // this code is now quite nested
            }
        }
    }

} catch (SomeException ex) {
    // some error-handling magic
}

:

DisposableObject obj1 = null;
DisposableObject obj2 = null;
DisposableObject obj3 = null;

try {
    obj1 = GetDisposableObject();
    // do something

    obj2 = GetAnotherDisposableObject();
    // do something else

    obj3 = GetYetAnotherDisposableObject();
    // do even more things

    // this code doesn't have to be nested

} catch (SomeException ex) {
    // some error-handling magic

} finally {
    if (obj3 != null) obj3.Dispose();
    if (obj2 != null) obj2.Dispose();
    if (obj1 != null) obj1.Dispose();
}

.

, . .

+2

using - .

fileshare.readwrite, .

0

Source: https://habr.com/ru/post/1732906/


All Articles