创建文件而不打开/锁定它?

有没有人知道一种方法(相当简单)创建一个文件而不实际打开/锁定它? 在File类中,文件创建方法始终返回FileStream。 我想要做的是创建一个文件,重命名它(使用File.Move),然后使用它。

现在我必须:

  • 创造它
  • 改名
  • 重新开放使用

也许你可以尝试使用文件名和空字符串的File.WriteAllText方法(字符串,字符串) 。

创建一个新文件,将指定的字符串写入该文件,然后关闭该文件。 如果目标文件已存在,则会被覆盖。

那么使用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. 
 using (File.Create(...)) { } 

虽然这短暂打开你的文件(但马上再次关闭),代码应该看起来非常不引人注目。

即使您对Win32 API函数执行了一些P / Invoke调用,也会得到一个文件句柄。 我不认为有一种方法可以在不事后打开的情况下静默创建文件。

我认为这里的真正问题是为什么要按照计划的方式创建文件。 在一个地方创建一个文件只是为了将其移动到另一个位置似乎不是很有效。 这有什么特别的原因吗?

难以置信的黑客攻击,可能是实现目标最复杂的方法:使用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

另一种方法是在创建文件后使用FileStream并关闭它。 它不会锁定文件。 代码如下所示:

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

fs.Flush(真);

fs.Close();

您可以在此之后重命名它或将其移动到其他位置。

下面是测试function的测试程序。

  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); } } } } 

如果您使用File.Create(在上面的代码中注释),那么它将给出错误,说文件正由另一个进程使用。