在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文件到D盘文件夹

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

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