You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用File.CreateText后StreamWriter无法访问文件及生成txt文件问题求助

问题1:文件占用IOException修复方案

  • 触发原因:File.CreateText()方法执行后会返回一个处于打开状态的StreamWriter对象,该对象会持有目标文件的句柄,你未释放该对象就直接实例化新的StreamWriter访问同一路径,就会触发进程占用异常。
  • 解决方法:无需单独调用File.CreateText()再实例化新的StreamWriter,直接复用File.CreateText()返回的StreamWriter对象即可,同时配合using关键字包裹IO对象,执行完逻辑后会自动释放资源,不需要手动处理释放逻辑。

问题2:生成txt格式文件修复方案

  • 触发原因:你的代码只有在首次生成的随机文件名已经存在的场景下,才会给新拼接的路径加.txt后缀,绝大多数首次生成的文件都没有后缀,自然不是txt格式。
  • 解决方法:拼接路径时统一给文件名加.txt后缀,同时文件是否存在的判断逻辑也要基于带后缀的完整路径进行,避免判断失效。

修正后完整代码

using System;
using System.IO;

namespace File_Dumping_Script
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rn = new Random();
            string dirPath = @"C:\Users\taylo\OneDrive\Desktop\FileTesting\";
            // 提前判断目录是否存在,不存在则创建避免报错
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            string fullPath;
            // 循环生成带txt后缀的文件名,直到找到不存在的文件路径
            do
            {
                string fileName = $"{rn.Next(1000)}.txt";
                fullPath = Path.Combine(dirPath, fileName);
            } while (File.Exists(fullPath));

            // using会自动释放StreamWriter资源,不会出现文件占用问题
            using StreamWriter sw = File.CreateText(fullPath);
            
            Console.Write("Please enter a seed for the random numbers: ");
            int seed = Convert.ToInt32(Console.ReadLine());
            int written = 0;
            while (written != seed - 1)
            {
                written = rn.Next(seed);
                sw.Write(" " + written);
                Console.WriteLine(written);
            }
            sw.Write("\n Process ended.");
            Console.WriteLine("Process complete.");
            Console.ReadLine();
        }
    }
}

内容的提问来源于stack exchange,提问作者cradaper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:57:02