c# - 如何从输入中设置txt文件字节
问题描述
我正在学习 c# 控制台。如果我们允许用户输入 1000 到 25000 之间的文件大小,该怎么做?我写了以下代码,但是当用户输入 1000 字节时,程序不会停止并且 txt 文件字节超过 1000 字节。(例如 27000)。
// user type file location C://files/files.txt
string randomword; // getting random words
int index;
try
{
Console.WriteLine("Please enter pathname of the file: ");
string pathOfFile = Console.ReadLine();
FileInfo fi = new FileInfo(pathOfFile);
long size = fi.Length;
if (fi.Exists)
{
// Get file size
Console.WriteLine("File Size in Bytes: {0}", size);
Console.WriteLine("Please enter the size of the file (min: 500 / max: 2500 : ");
long fileOfSize = int.Parse(Console.ReadLine());
if (size > fileOfSize)
{
Environment.Exit(0);
}
else
{
for (index = 1; index <= fileOfSize; index++)
{
randomword= gettingRandomWord() + Environment.NewLine;
File.AppendAllText(pathOfFile, randomword);
}
}
}
}
catch (Exception ex)
{
}
解决方案
默认情况下,文件采用 UTF-8 格式,因此单个字符可以包含多个写入文件的字节。您正在将 和 的结果添加到一个新字符串中gettingRandomWord()
并将Environment.NewLine
其附加到文件中。在 Windows 上,这将始终超过一个字节,而 WindowsEnvironment.NewLine
本身就是两个字节。您每次通过循环仅将索引增加一个字节。
您需要获取将写入文件的字节数,并在每次循环迭代时将索引增加该数量。要获取将添加的字节数:
var byteCountToBeWritten = System.Text.Encoding.UTF8.GetByteCount(randomword);
作为提示,for
表达式的最后一部分是可选的,因此您可以i
在循环内递增。如果您根本不想超过字节数,您将需要不同的策略。
推荐阅读
- c++ - gluLookAt 不断旋转相机
- akeneo - 带有状态和批量操作的 Akeneo 错误
- javascript - @azure/msal-angular 的元数据版本不匹配
- c++ - put_time() 忽略时区偏移的转换说明符“z”
- keras - 将权重加载到 VGG16 模型时如何解决“TypeError: +: 'int' and 'str' 的不支持的操作数类型”
- batch-file - 如何在批处理脚本中隐藏 MD 和 MOVE 命令的输出消息?
- soap - 在 WSDL 中包含 XML 格式
- javascript - 根据背景颜色更改多个元素颜色
- java - 有没有一种有效的方法来连接两个带有(更深)嵌套数组字段的大型数据集?
- codeigniter - 找不到 Codeigniter 404 页面,如何设置