tags:

views:

231

answers:

4

Hi,

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
+2  A: 

What about using File.WriteAllBytes method?

// Summary:
//     Creates a new file, writes the specified byte array to the file, and then
//     closes the file. If the target file already exists, it is overwritten.
Rubens Farias
+3  A: 

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.

astander
That's a good idea!
kaze
A: 
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?

stakx
Reason: http://stackoverflow.com/questions/2109152/unbelievable-strange-file-creation-time-problem
kaze
OK, fair enough. Interesting Windows "feature". :-/
stakx
+1  A: 

Incredibly grotty hack, probably the most complicated way to achieve your goal: use Process class

processInfo = new ProcessStartInfo("cmd.exe", "/C " + Command);
processInfo.CreateNoWindow = true; 
processInfo.UseShellExecute = false;
process = process.Start(processInfo);
process.WaitForExit();

where Command would be echo 2>> yourfile.txt

Bolek Tekielski
+1, for thinking outside the box
Rubens Farias