Home > Net >  C# - Writing to file with filestream
C# - Writing to file with filestream

Time:03-18

Is this the correct way of using Filestream? If so, is there anything i can improve in this function? Its mainly planned, to be used to write to an ftp-folder, containing 600 lines of data.

My concern is the for loop.

This is my first time using C# for work. So i can use the advice.

private void button3_Click(object sender, EventArgs e)
        {//FINISH BUTTON
            if (string.IsNullOrEmpty(FilePathBox.Text) || string.IsNullOrEmpty(FileNameBox.Text))
            {
                MessageBox.Show("Please check folderpath or filename.", 
                    "WARNING");
            }
            else
            {
                String vFullPath = FilePathBox.Text   "/"   FileNameBox.Text   ExtentionBox.Text;
                MainProgressBar.Maximum = OutputBox.Items.Count;

                using (FileStream fs = File.Create(vFullPath))
                {

                    for (int i = 0; i < OutputBox.Items.Count; i  )
                    {
                        //String vInput = OutputBox.Items[i].ToString()   "\n";
                        //File.AppendAllText(vFullPath, vInput);
                        String vInput = OutputBox.Items[i].ToString()   "\n";
                        byte[] vData = new UTF8Encoding(true).GetBytes(vInput);
                        fs.Write(vData, 0, vData.Length);
                        MainProgressBar.Value = i;
                    }
                }

                MainProgressBar.Value = MainProgressBar.Maximum;
                MessageBox.Show("Finished Writing to file.",
                    "Completed");
            }
        } 

CodePudding user response:

A more typical approach would be to wrap the stream in a StreamWriter, this has write methods for strings , removing the need to convert everything to bytes. You can select the encoding in the constructor. There is also a BinaryWriter for writing binary data.

Writing data in a loop is not a problem. You could perhaps create a complete string in memory with String.Join instead, and use File.WriteAllLines, but I would not expect very much to be gained.

My preferred method for reporting progress is to run the work on a background thread using Task.Run, set a property describing the progress in a shared object, and create a timer on the UI thread that polls said property and updates the progress-bar. That helps ensure the UI is responsive.

I would also consider using some kind of serialization library, like json.net. This greatly simplifies the process of turning a object into a file and back again. But it is less relevant for things like logging.

  • Related