ankit goel
ankit goel

Reputation: 43

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);
        } 

Upvotes: -1

Views: 323

Answers (3)

ankit goel
ankit goel

Reputation: 43

The problem is solved. With my updated code as suggested by @Tim Schmelter and from the help by this link C# access to the path is denied...(System.UnauthorizedAccessException: Access to the path 'C:\' is denied.), I now can see the file with all the contents written to it.

 string file = @"D:\textWriter.txt";
        // check if the file exists
        try
        {
            if (File.Exists(file))
            {
                File.Delete(file);
            }
            else
            {
                File.WriteAllLines(file, list2);
            }
        }
        catch (Exception Op)
        {
            MessageBox.Show(Op.Message);
        }
    

Upvotes: 0

Klo
Klo

Reputation: 23

You have different pathes in (File.Exists(file) and File.CreateText(@"SavedList.txt"). Next, did u add elements in List?

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460078

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

Upvotes: -1

Related Questions