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

问题描述 投票:0回答:5

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

现在我必须:

  • 创建它
  • 关闭
  • 重命名
  • 重新开放使用
c# .net file-io
5个回答
10
投票

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

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


4
投票
using (File.Create(...))  { }

虽然这短暂地打开您的文件(但立即再次关闭它),但代码应该看起来相当不引人注目。

即使您对 Win32 API 函数进行了一些 P/Invoke 调用,您也会获得一个文件句柄。我认为没有办法在不立即打开文件的情况下静默创建文件。

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


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
投票

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

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

fs.Flush(true);

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


1
投票

令人难以置信的黑客攻击,可能是实现目标的最复杂的方法: 使用

Process

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

命令将是

echo 2>> yourfile.txt

© www.soinside.com 2019 - 2024. All rights reserved.