如何在 C# 中写入文件并随后删除文件?

How can I write to a file and remove the file afterwards in C#?

我需要创建一个文件,在文件中写入一行文本然后删除文件并估计需要多长时间。

不幸的是,我 运行 遇到了几个问题,首先我无法写入文件,它成功创建了它,但没有写入任何内容。

其次,我无法删除该文件,因为它已被另一个进程使用。

请帮忙。

我已经尝试删除它很长一段时间了。

我也试过用 usings 包装它,但无济于事。

写入文件也是一样的情况。我什至更改了它,使文件以 .txt 结尾,但这没有任何区别。

        public static void ProcessFile(string path)
        {
        string fullpath = path;
        int lastBracket = path.LastIndexOf("\");
        // the filename does not contain .html so it can be named to .txt
        string newFileName = path.Substring(lastBracket + 1, path.Length - lastBracket - 6) + " hrefcount.txt";
        string newPath = Path.Combine(fullpath.Substring(0, lastBracket), newFileName);
        Console.WriteLine(newPath);
        int counter = 0;
            foreach (var line in File.ReadAllLines(path))
            {
                if (line.Contains("href="))
                {
                counter++;
                }
            }

        var fileCreated = File.CreateText(newPath);
        fileCreated.WriteLine("The number of times href appears is " + counter);
        Console.WriteLine();
        File.Delete(newPath);
    }

文件已创建,未写入任何内容,由于已被另一个进程使用而无法删除。

而不是 File.CreateText() 使用 File.WriteAllText(path, content)。它写入文本,然后关闭文件,允许您在必要时删除它

而不是下面的

var fileCreated = File.CreateText(newPath);
fileCreated.WriteLine("The number of times href appears is " + counter);

你可以写

File.WriteAllText(newPath, $"The number of times href appears is {counter}");

参考文档here

您的方法的问题在于 CreateText() 用于写入流。但在您的情况下,没有必要,因为您是一次将所有文本写入文件并且该文本的大小很小。

I cannot delete the file because it has been used by another process.

可能您在创建后没有处理文件。为此,您还应该使用 FileStream.Dispose 方法:

File.Create(path).Dispose();


estimate how long it will take to do it

您可以使用 System.Diagnostics.Stopwatch class 来做到这一点:

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
/*
   do the magic
*/
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);


您可以使用 File.WriteAllText 方法而不是 File.CreateText 将文本写入文件:

File.WriteAllText(path, myText);

请记住,从 .NET 4 开始,您可以将此方法用于数组或 List<T> 而不是字符串。

File.Create() 支持 Dispose 方法,帮助您释放该文件资源以执行进一步的操作

要对文件执行操作,请按照以下步骤操作:

  1. 使用 Dispose() 创建文件并释放资源。

    File.Create(newPath).Dispose();

或使用StreamWriter创建文件并向其中写入文本。

using( StreamWriter sw = new StreamWriter(newPath, true)
{
   sw.Write($"The number of times href appears is {counter}"); //Used string interpolation 
}

StreamWriter调用Dispose()函数释放文件资源。

当 Writer 释放对文件的控制时,您将不会遇到与 我无法删除该文件,因为它已被另一个进程使用。

相关的问题

现在您可以使用

删除文件
  1. File.Delete(新路径);

MSDN:IDisposable.Dispose Method

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

错误的原因是您没有关闭和释放变量 fileCreated。这是一个 FileStream,在您关闭并处置此变量之前,任何人都无法使用该文件,即使是您自己打开该文件的代码也是如此。

所以首先要做的是

using (var fileCreated = File.CreateText(newPath))
{
    fileCreated.WriteLine("The number of times href appears is " + counter);
}

using 块确保正确处理变量。

但是,您可以简化代码的其他部分

public static void ProcessFile(string path)
{
    string folder = Path.GetDirectoryName(path);
    string file = Path.GetFileName(path);


    // Keep the first 6 characters from the source file?
    string newFile = file.Substring(0, 6) + " hrefcount.txt";
    string newPath = Path.Combine(folder, newFile);

    // A single line to retrieve your counter thanks to IEnumerables and Linq
    int counter = File.ReadLines(path).Count(x => x.Contains("href="));

    // Create, but dispose also the file
    using (var fileCreated = File.CreateText(newPath))
    {
        fileCreated.WriteLine("The number of times href appears is " + counter);
    }

    // Now you should be free to delete the file
    File.Delete(newPath);
}