Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create file without opening/locking it?

Tags:

c#

.net

file-io

Does anyone know of a way to (reasonably simple) create a file without actually opening/locking it? In File class, the methods for file creation always return a FileStream. What I want to do is to create a file, rename it (with File.Move) and then use it.

Now I have to:

  • Create it
  • Close
  • Rename
  • Reopen for use
like image 753
kaze Avatar asked Jan 22 '10 09:01

kaze


2 Answers

Maybe you can try using File.WriteAllText Method (String, String) with the file name and an empty string.

Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

like image 121
Adriaan Stander Avatar answered Sep 17 '22 17:09

Adriaan Stander


using (File.Create(...))  { }

While this will briefly open your file (but close it again right away), the code should look quite unobtrusive.

Even if you did some P/Invoke call to a Win32 API function, you would get a file handle. I don't think there's a way to silently create a file without having it open right afterwards.

I think the real issue here is why you go about creating your file in the way you've planned. Creating a file in one place simply to move it to another location doesn't seem very efficient. Is there a particular reason for it?

like image 24
stakx - no longer contributing Avatar answered Sep 21 '22 17:09

stakx - no longer contributing