0

hello,now I want to create a text file to save my output and then need to open and read again. Who knows how to do that? Can teach me..?

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by Mitja Bonca
0

Check out this code:

private void buttonWrite_Click(object sender, EventArgs e)
        {
            List<string> list = new List<string>(new string[] { "a,", "b", "c" }); //out put example
            CreateAndWriteIntoFile(list);
        }

        private void buttonRead_Click(object sender, EventArgs e)
        {
            List<string> list = ReadFromFile();
        }

        private void CreateAndWriteIntoFile(List<string> list)
        {
            string path = @"C:\MyFolder\myFile.txt";
            using (FileStream fs = new FileStream(path, FileMode.CreateNew))
            {
                //now when file is created you can write into it:
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    foreach (string name in list)
                        sw.WriteLine(name);
                }
            }
        }

        private List<string> ReadFromFile()
        {
            string path = @"C:\MyFolder\myFile.txt";
            List<string> list = new List<string>();
            using (StreamReader sr = new StreamReader(path))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                    list.Add(line);
            }
            return list;
        }

Mitja

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.