user3473957
user3473957

Reputation: 89

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.
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). I created a file (manually) that contain the number 1(digit) and compare it(hash) with the other one... they are not the same! But they contain equal string, in this case "1".

Upvotes: 2

Views: 392

Answers (3)

Kuree
Kuree

Reputation: 118

You should try 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.

Upvotes: 0

Ross Bush
Ross Bush

Reputation: 15175

I bet that WriteLine is adding a carriage return which is cr/lf. That would be two extra bytes. If you use Write does the problem go away?

Upvotes: 8

whoisj
whoisj

Reputation: 388

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. Also, explicitly use ASCII encoding - otherwise you'll likely end up with a UTF BOM prefix - which it seems you do not want.

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

Upvotes: 1

Related Questions