-2

I am trying to create a new file with a specific length. By using below code, the file gets created. The problem is the length of the file created is 0kb's. Also, the text under stream writer is not written in the file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;

namespace Filesize
{
class Program
{
    static void Main(string[] args)
    {
        FileInfo fi = new FileInfo(@"D:\\demotext2.txt");
        StreamWriter sw = new StreamWriter(@"D:\\demotext2.txt", true);
            try
            {
                while (fi.Length >= (2 * 1024 * 1024))
                {

                        sw.WriteLine("Demo File");

                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }
    }
}
  • 4
    Step through the code in a debugger. It should be fairly obvious from there. – Willem van Rumpt Apr 03 '15 at 08:11
  • 2
    Should it be `fi.Length <= (2 * 1024 * 1024)` – Carbine Apr 03 '15 at 08:12
  • possible duplicate of [Creating a Huge Dummy File in a Matter of Seconds in C#](http://stackoverflow.com/questions/1881050/creating-a-huge-dummy-file-in-a-matter-of-seconds-in-c-sharp) – Youngjae Apr 03 '15 at 08:13
  • @CarbineCoder has probably answered your question. You should also be aware that just calling `ToString` on your exception won't give you any information. Do you want `Console.WriteLine(ex.ToString());`? – Wai Ha Lee Apr 03 '15 at 08:18

1 Answers1

2

Try to use this: http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength.aspx

using (var fs = new FileStream(strCombined, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        fs.SetLength(oFileInfo.FileSize);
    }
Behzad
  • 3,502
  • 4
  • 36
  • 63