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

时间:2010-01-22 09:14:22

标签: c# .net file-io

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

现在我必须:

  • 创建
  • 关闭
  • 重命名
  • 重新开放使用

5 个答案:

答案 0 :(得分:8)

也许您可以尝试使用File.WriteAllText Method (String, String) 文件名和空字符串。

  

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

答案 1 :(得分:2)

使用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 :(得分:2)

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

虽然 会暂时打开您的文件(但会立即再次关闭),但代码应该看起来非常不引人注目。

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

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

答案 3 :(得分:1)

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

答案 4 :(得分:1)

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

  

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

     

fs.Flush(真);

     

fs.Close();

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

以下是测试功能的测试程序。

   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(在上面的代码中注释),那么它会给出错误,说文件正由另一个进程使用。

相关问题