在 C# 中,可以使用 System.IO 命名空间中的 File 类来生成 TXT 文件。下面是一个示例代码,演示了如何在多线程中生成 TXT 文件到 D 盘文件夹:

using System;
using System.IO;
using System.Threading;

class Program
{
    static void Main()
    {
        // 创建多个线程
        for (int i = 0; i < 5; i++)
        {
            Thread thread = new Thread(GenerateTextFile);
            thread.Start();
        }

        Console.ReadLine();
    }

    static void GenerateTextFile()
    {
        string fileName = $'D:\file_{Thread.CurrentThread.ManagedThreadId}.txt';
        string content = $'This is the content of file_{Thread.CurrentThread.ManagedThreadId}.txt';

        // 写入文件
        File.WriteAllText(fileName, content);

        Console.WriteLine($'Thread {Thread.CurrentThread.ManagedThreadId} generated file {fileName}');
    }
}

在上述示例中,我们首先创建了 5 个线程,并分别启动了这些线程。每个线程调用 GenerateTextFile 方法来生成一个 TXT 文件。文件名使用线程 ID 来标识,以避免文件名冲突。然后,我们使用 File.WriteAllText 方法将文本内容写入文件。最后,我们在控制台输出线程 ID 和生成的文件名。

C# 多线程生成 TXT 文件到指定目录

原文地址: https://www.cveoy.top/t/topic/qvhp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录