In .Net, using File.CreateText () also blocks the file, why?

I used the CreateText method to create an empty file (as shown below) in "App1". Then I tried to write another application to this file, but it failed b / c, it was blocked. It was not unlocked until I closed "App1"

File.CreateText(path)

To fix this, I can do this:

Dim sw As StreamWriter = File.CreateText(path)
sw.Close()

Why does calling only CreateText lock the file? Is there any implicit stream or script file or something created?

tep

+3
source share
8 answers

Yes Yes. CreateText()returns the object StreamWriterthat is open for the file you specified.

, StreamWriter , . , .

+7

- ?

StreamWriter, . StreamWriter.

:

File.CreateText(path).Close()

.

+5

CreateText() , StreamWriter, , .

, ( ).

+2

, :

File.WriteAllBytes(path, new byte[0]);
+1

File.CreateFile StreamWriter FileStream, FileMode.Create, FileAccess.Write FileShare.Read. , . , , , . , , , .

, , , File.CreateFile(). FileStream (Create, Write FileShared.ReadWrite) StreamWriter. , .

, , - . , , , . , .

, - , . , . , . , , , , .

+1

, StreamWriter. . . .

0

, - -, .

Module Tools
  Sub CreateTextNoLock(ByVal text as String)
    Dim sw = File.CreateText(text)
    sw.Close
  End Sub
End Module
0

StreamWriter , close. ( ), "" GC.

Using sw As StreamWriter = File.CreateText(path)
    sw.Write("")
End Using
0

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


All Articles