首页 > 解决方案 > 如何从输入中设置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)
{
}

标签: c#

解决方案


默认情况下,文件采用 UTF-8 格式,因此单个字符可以包含多个写入文件的字节。您正在将 和 的结果添加到一个新字符串中gettingRandomWord()并将Environment.NewLine其附加到文件中。在 Windows 上,这将始终超过一个字节,而 WindowsEnvironment.NewLine本身就是两个字节。您每次通过循环仅将索引增加一个字节。

您需要获取将写入文件的字节数,并在每次循环迭代时将索引增加该数量。要获取将添加的字节数:

var byteCountToBeWritten = System.Text.Encoding.UTF8.GetByteCount(randomword); 

作为提示,for表达式的最后一部分是可选的,因此您可以i在循环内递增。如果您根本不想超过字节数,您将需要不同的策略。


推荐阅读