C#控制台程序实现用户指定1000-25000字节文本文件大小的问题解决方案
我帮你搞定这两个问题,先给你修正后的完整代码,再详细解释改了哪些地方:
修正C#控制台程序的文件大小控制问题
using System; using System.IO; class Program { static void Main(string[] args) { string randomWord; try { Console.WriteLine("Please enter pathname of the file: "); string pathOfFile = Console.ReadLine(); // 处理文件不存在的情况:自动创建空文件 FileInfo fi = new FileInfo(pathOfFile); if (!fi.Exists) { using (File.Create(pathOfFile)) {} Console.WriteLine("Created new empty file at the specified path."); } long currentSize = fi.Length; Console.WriteLine("Current File Size in Bytes: {0}", currentSize); // 修正输入提示范围,同时添加严格的输入验证 long targetSize; while (true) { Console.WriteLine("Please enter the target file size (min: 1000 / max: 25000 bytes): "); string input = Console.ReadLine(); if (long.TryParse(input, out targetSize)) { if (targetSize >= 1000 && targetSize <= 25000) { break; } else { Console.WriteLine("Oops! Size must be between 1000 and 25000 bytes. Try again."); } } else { Console.WriteLine("Invalid input! Please enter a valid number."); } } // 当前文件已达标则直接退出 if (currentSize >= targetSize) { Console.WriteLine("File already meets or exceeds the target size. Exiting..."); Environment.Exit(0); } // 用StreamWriter高效写入,避免频繁打开关闭文件 using (StreamWriter writer = File.AppendText(pathOfFile)) { while (currentSize < targetSize) { randomWord = gettingRandomWord() + Environment.NewLine; // 计算当前要写入内容的字节数(默认UTF-8编码) byte[] contentBytes = System.Text.Encoding.UTF8.GetBytes(randomWord); // 防止写入后超出目标大小,必要时截取内容 if (currentSize + contentBytes.Length > targetSize) { long remainingBytes = targetSize - currentSize; string truncatedContent = System.Text.Encoding.UTF8.GetString(contentBytes, 0, (int)remainingBytes); writer.Write(truncatedContent); currentSize += remainingBytes; } else { writer.Write(randomWord); currentSize += contentBytes.Length; } } } Console.WriteLine($"Done! Final file size: {new FileInfo(pathOfFile).Length} bytes."); } catch (Exception ex) { Console.WriteLine($"Something went wrong: {ex.Message}"); } } // 假设这是你已经实现的随机单词生成方法 static string gettingRandomWord() { string[] words = {"apple", "banana", "cherry", "date", "elderberry"}; Random rand = new Random(); return words[rand.Next(words.Length)]; } }
核心修改说明
1. 修正输入提示与范围验证
- 把输入提示里的范围从
500-2500改成了需求的1000-25000 - 加了循环验证逻辑:
- 用
long.TryParse替代int.Parse,避免用户输入非数字时程序崩溃 - 强制检查输入数值是否在指定范围内,不符合就提示重新输入
- 用
2. 彻底修复文件大小控制逻辑
- 原代码的
for (index = 1; index <= fileOfSize; index++)完全错误:循环次数不等于字节数,每个随机单词+换行的字节数远大于1,导致最终文件大小严重超标 - 改成了基于字节数的精准控制:
- 先计算当前文件与目标大小的差值
- 每次写入前计算要写内容的字节数,确保不会超过目标
- 如果当前内容会导致超标,就截取部分内容写入,保证最终大小完全符合要求
3. 其他实用优化
- 新增了文件不存在时的自动创建逻辑,避免原代码中文件不存在就跳过写入的问题
- 用
StreamWriter替代File.AppendAllText,减少文件反复打开关闭的开销,提升效率 - 修复了原代码的退出逻辑:把
if (size > fileOfSize)改成currentSize >= targetSize,覆盖了文件刚好达标的情况 - 去掉了空的
catch块,添加了错误信息输出,方便调试 - 最后加了最终文件大小的确认提示,让用户直观看到结果
内容的提问来源于stack exchange,提问作者suakinos
相关产品推荐
相关产品推荐

