简体   繁体   English

如何创建没有标题的文件

[英]How to create file with no headers

I need to create 100 files and every file to contain only a number between 1 and 100. 我需要创建100个文件,每个文件只包含1到100之间的数字。
I am usinig this code: 我是这样的代码:

for (int i = 1; i <= 100; i++)
{
     TextWriter tw = new StreamWriter(i.ToString(), true);

     tw.WriteLine(i.ToString());
     tw.Close(); 

}

It's work but the files are bigger than expected (3 bytes). 它工作但文件比预期的大(3个字节)。 I created a file (manually) that contain the number 1(digit) and compare it(hash) with the other one... they are not the same! 我创建了一个包含数字1(数字)的文件(手动),并将其与另一个文件进行比较(哈希)......它们不一样! But they contain equal string, in this case "1". 但它们包含相等的字符串,在本例中为“1”。

I bet that WriteLine is adding a carriage return which is cr/lf. 我敢打赌,WriteLine正在添加一个cr / lf的回车。 That would be two extra bytes. 这将是两个额外的字节。 If you use Write does the problem go away? 如果使用Write,问题会消失吗?

Use the File.WriteAllText method, it's easier in this case and does a better job of cleaning up after itself that you're doing. 使用File.WriteAllText方法,在这种情况下更容易,并且可以更好地清理自己正在进行的操作。 Also, explicitly use ASCII encoding - otherwise you'll likely end up with a UTF BOM prefix - which it seems you do not want. 此外,明确使用ASCII编码 - 否则您可能最终会得到一个UTF BOM前缀 - 这似乎是您不想要的。

for (int i = 0; i < 100; i++)
{
    string istr = i.ToString();
    System.IO.File.WriteAllText(istr, istr + ".txt", System.Text.Encoding.ASCII);
}

You should try BinaryWeiter . 你应该尝试BinaryWeiter

for (int i  = 0; i < 100; i++)
{
   using(MemoryStream ms = new MemoryStream())
   {
      BinaryWriter w = new BinaryWriter(ms);
      w.Write(i.ToString());
   }
}

This will write length prefixed string into the stream. 这会将长度为前缀的字符串写入流中。 You can use FileStream if you want to save it to the disk. 如果要将其保存到磁盘,可以使用FileStream。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM