Create file without opening / locking?

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

Now I have to:

  • Create it
  • Close
  • Rename
  • Reopen for use
+3
source share
5 answers

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

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

+8

File.WriteAllBytes?

// 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.
+2
using (File.Create(...))  { }

( ), .

P/Invoke Win32 API, . , , .

, , , . . ?

+2

, , : Process

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

Command echo 2>> yourfile.txt

+1

Another way is to use FileStream and close it after creating the file. It will not lock the file. The code will look like this:

FileStream fs = new FileStream (filePath, FileMode.Create);

fs.Flush (true);

fs.Close ();

After that, you can rename it or move it to another place.

The following is a test program for testing functionality.

   using System; 
   using System.Collections.Generic; 
   using System.IO; using
   System.Linq;
   using System.Text; 
   namespace FileLocking {
   class Program
   {
    static void Main(string[] args)
    {
        string str = @"C:\Test\TestFileLocking.Processing";
        FileIOTest obj = new FileIOTest();
        obj.CreateFile(str);
    }
}

class FileIOTest
{
    internal void CreateFile(string filePath)
    {
        try
        {
            //File.Create(filePath);

            FileStream fs = new FileStream(filePath, FileMode.Create);
            fs.Flush(true);
            fs.Close();

            TryToAccessFile(filePath);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    void TryToAccessFile(string filePath)
    {
        try
        {
            string newFile = Path.ChangeExtension(filePath, ".locked");
            File.Move(filePath, newFile);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
} }

If you use File.Create (commented out in the code above), then it will throw an error saying that the file is being used by another process.

+1
source

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


All Articles