简体   繁体   中英

Getting,reading,writing, and saving into one .txt file a collection of .txt documents contents. in visual c# using windows form

am new to c#,Here am trying to read multiple txt files with its contents at once, then using textbox to collect all the txt content, after collecting the content then I will save all the content back into once txt file. below is my code, pls help out.

Here is the interface of the app

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace FileSaver
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        //File 004: Save the File in System Temporary path
        private void button2_Click(object sender, EventArgs e)
        {
            if (txtFileContent.Visible == true)
            {
                SaveFile(Path.GetTempPath());
            }
            else
                MessageBox.Show("This form saves only text files");
        }



        //File 001: Use File open dialog to get the file name
        private void btn_File_Open_Click(object sender, EventArgs e)
        {
           List<String> MyStream = new List<string>();
            string ext = "";


               this.dlgFileOpen.Filter = "Text Files(*.txt) | *.txt";
               this.dlgFileOpen.Multiselect = true;



            if (dlgFileOpen.ShowDialog() == DialogResult.OK)
            {
                try
                {

                    StringBuilder stbuilder = new StringBuilder();

                    foreach (var files in dlgFileOpen.SafeFileNames )
                    {
                        MyStream.Add(files + "\n");
                        Console.WriteLine();
                    }


                    foreach (var item in MyStream)
                    {
                        stbuilder.Append(item );
                    }

                    txtSelectedFile.Text = stbuilder.ToString() ;
                    ext = Path.GetExtension(dlgFileOpen.FileName);


                }
                catch (Exception ex)
                {

                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }




                if (ext == ".txt")
                {
                    //003: The extension is txt. Read the file and display the content
                    txtFileContent.Visible = true;


                    FileStream filestream = new FileStream(dlgFileOpen.FileName, FileMode.Open);
                    StreamReader streamReader = new StreamReader(filestream);

                    while (streamReader.EndOfStream != true)
                    {

                        txtFileContent.AppendText(streamReader.ReadLine());

                        txtFileContent.AppendText(Environment.NewLine);

                    }

                    streamReader.Close();

                }
            }
        }

        private void txtSelectedFile_TextChanged(object sender, EventArgs e)
        {

        }

        //File 002: Use the Path object to determine the selected file has the

        // required extension.
        private void dlgFileOpen_FileOk(object sender, CancelEventArgs e)
        {

            string Required_Ext = ".txt ";

            string selected_ext = Path.GetExtension(dlgFileOpen.FileName);

            int index = Required_Ext.IndexOf(selected_ext);

            //002: Inform the user to select correct extension

            if (index < 0)
            {

                MessageBox.Show("Extension Maaaan... Extension! Open only txt or bmp or jpg");

                e.Cancel = true;

            }
        }

        private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
        {


        }

        private void SaveFile_Click(object sender, EventArgs e)
        {
            //001: Setup the Folder dialog properties before the display
            string selected_path = "";
            dlgFolder.Description = "Select a Folder for Saving the text file";
            dlgFolder.RootFolder = Environment.SpecialFolder.MyComputer;

            //002: Display the dialog for folder selection
            if (dlgFolder.ShowDialog() == DialogResult.OK)
            {
                selected_path = dlgFolder.SelectedPath;
                if (string.IsNullOrEmpty(selected_path) == true)
                {
                    MessageBox.Show("Unable to save. No Folder Selected.");
                    return;
                }
            }

            //003: Perform the File saving operation. Make sure text file is displayed before saving.
            if (txtFileContent.Visible == true)
            {
                SaveFile(selected_path);
            }
            else
                MessageBox.Show("This form saves only text files");


        }

        public void SaveFile(string selected_path)
        {
            string Save_File;
            if (selected_path.Length > 3)
                Save_File = selected_path + "\\" + txtSaveFile.Text + ".txt";
            else
                Save_File = selected_path + txtSaveFile.Text + ".txt";
            FileStream fstream = new FileStream(Save_File, FileMode.CreateNew);
            StreamWriter writer = new StreamWriter(fstream);
            writer.Write(txtFileContent.Text);
            lblSavedLocation.Text = "Text File Saved in " + Save_File;
            writer.Close();
        }

        private void txtSaveFile_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

Try this out. I stripped out all the the code i felt unnecessary for your problem:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace FileSaver
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {
        }

        private void label1_Click(object sender, EventArgs e)
        {
        }

        //File 004: Save the File in System Temporary path
        private void button2_Click(object sender, EventArgs e)
        {
            if (txtFileContent.Visible == true)
            {
                SaveFile(Path.GetTempPath());
            }
            else
                MessageBox.Show("This form saves only text files");
        }

        //File 001: Use File open dialog to get the file name
        private void btn_File_Open_Click(object sender, EventArgs e)
        {
            this.dlgFileOpen.Filter = "Text Files(*.txt) | *.txt";
            this.dlgFileOpen.Multiselect = true;

            if (dlgFileOpen.ShowDialog() == DialogResult.OK)
            {
                var stBuilder = new StringBuilder();

                foreach (var fileName in dlgFileOPen.FileNames)
                {
                    stBuilder.AppendLine(File.ReadAllText(fileName));
                }

                txtFileContent.Text = stBuilder.ToString();
            }
        }

        private void txtSelectedFile_TextChanged(object sender, EventArgs e)
        {
        }

        //File 002: Use the Path object to determine the selected file has the

        // required extension.
        private void dlgFileOpen_FileOk(object sender, CancelEventArgs e)
        {
        }

        private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
        {
        }

        private void SaveFile_Click(object sender, EventArgs e)
        {
            //001: Setup the Folder dialog properties before the display
            string selected_path = "";
            dlgFolder.Description = "Select a Folder for Saving the text file";
            dlgFolder.RootFolder = Environment.SpecialFolder.MyComputer;

            //002: Display the dialog for folder selection
            if (dlgFolder.ShowDialog() == DialogResult.OK)
            {
                selected_path = dlgFolder.SelectedPath;
                if (string.IsNullOrEmpty(selected_path) == true)
                {
                    MessageBox.Show("Unable to save. No Folder Selected.");
                    return;
                }
            }

            //003: Perform the File saving operation. Make sure text file is displayed before saving.
            if (txtFileContent.Visible == true)
            {
                SaveFile(selected_path);
            }
            else
                MessageBox.Show("This form saves only text files");
        }

        public void SaveFile(string selected_path)
        {
            string Save_File;
            if (selected_path.Length > 3)
                Save_File = selected_path + "\\" + txtSaveFile.Text + ".txt";
            else
                Save_File = selected_path + txtSaveFile.Text + ".txt";

            File.WriteAllText(Save_File, txtFileContent.Text);
            lblSavedLocation.Text = "Text File Saved in " + Save_File;
        }

        private void txtSaveFile_TextChanged(object sender, EventArgs e)
        {
        }
    }
}

All looks good, except for the reading part, it can be done in a much easier way....

StringBuilder stbuilder = new StringBuilder();

                foreach (var filePath in dlgFileOpen.FileNames)
                {
                    StreamReader sr = new StreamReader(filePath);
                    stbuilder.Append(sr.ReadToEnd());
                    sr.Close();

//Or Much faster you can use 
                    stbuilder.Append(File.ReadAllText(filePath));
                    stbuilder.Append(Environment.NewLine);


                    stbuilder.Append(Environment.NewLine);
                    txtFileContent.Text = stbuilder.ToString();
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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