Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to Save all the elements of a List to a text file

I am trying to save all the contents of a List into a text file but I am unable to do . Below is the code that I have tried

 // here is my list type 
 List<string> list2 = new List<string>();

 //code below for saving the contents of the list into text file 
 string file = @"C:\Users\textWriter.txt";
        // check if the file exists
        try
        {
            if (File.Exists(file))
            {
                File.Delete(file);
            }
            else
            {
                using (TextWriter tw = File.CreateText(@"SavedList.txt"))
                {
                    foreach (String s in list2)
                        tw.WriteLine(s);
                }
            }
        }
        catch (Exception Op)
        {
            MessageBox.Show(Op.Message);
        } 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Not sure what is the exception but i strongly recommend to use this instead:

File.WriteAllLines(file, list2);

If the target file already exists, it is overwritten.

Documentation: File.WriteAllLines


In your code you are using different paths, maybe that’s the reason

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading