I have been reading books trying to learn .net on my own. I am working on an exercise that asks me to create a 1MB file. what i have below does work, but it seems to me there would be a more efficeient way. It seems like what i am doing would cause a lot of overhead. Any advice for making a 1MB file easier than what i have? =)

Module Module1

    Sub Main()

        Dim fileName As String = "myfile.txt"

        Dim fileInfo As New FileInfo(fileName)
        Dim length As Integer = 0
        Dim MB As Integer = 1048576
        Do
            If File.Exists(fileName) Then
                Dim stream As StreamWriter = File.AppendText(fileName)
                length = fileInfo.Length()
                stream.WriteLine("HELLO WORLD sfldkjsdlfjsdklfjklsjfklsd")
                stream.Flush()
                stream.Close()
            Else
                Dim stream As StreamWriter = File.CreateText(fileName)
                stream.WriteLine("HELLO WORLD HELLO WORLD!!!!")
                stream.Flush()
                stream.Close()
            End If
            
            length += fileInfo.Length

        Loop Until length >= MB

    End Sub

End Module

Here is something that will get you 1 MB exactly, although someone else might do it better.

Sub Main()
        Dim megabyte As Integer = 1024 * 1024 - 1
        Dim buffer(megabyte) As Char

        For i As Integer = 0 To buffer.Length - 1
            'just to vary the output
            If i Mod 3 = 0 Then
                buffer(i) = "_"c
            ElseIf i Mod 2 = 0 Then
                buffer(i) = "1"c
            Else
                buffer(i) = "0"c
            End If
        Next

        Dim writer As New System.IO.StreamWriter("C:\Temp\megabytefilevb.txt")
        writer.Write(buffer)
        writer.Close()
        writer.Dispose()

    End Sub
static void Main()
        {
            int megabyte = 1024 * 1024;
            char[] buffer = new char[megabyte];

            for (int i = 0; i < buffer.Length ; i++)
            {
                // just to vary the output
                if (i % 3 == 0)
                    buffer[i] = '_';
                else if (i % 2 == 0)
                    buffer[i] = '1';
                else 
                    buffer[i] = '0';
            }

            System.IO.StreamWriter writer = new System.IO.StreamWriter (@"C:\Temp\megabytefile.txt");
            writer.Write(buffer);
            writer.Close();
            writer.Dispose();            
        }

Thank you!. I knew i was doing too much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.