-2

I'm trying to export some data to a txt file, but it doesn't work since I get unauthorized exception.

I tried running visual studio as admin, but it didn't work

This is the code I have:

  TextWriter txt = new StreamWriter(path);
  for (int i = 0; i < Movies.Count; i++)
  {
     txt.WriteLine(Movies[i].title);
  }
  txt.Close();

The path is correct

tonga
  • 191
  • 3
  • 12
  • 1
    What is the value of `path`? Does your user have access to that file? Does the exception have any additional information? Is the file currently in use by another (or the same) process? – gunr2171 Oct 13 '22 at 17:01
  • @gunr2171 I'm trying to export the file to my desktop, and the exception says: System.UnauthorizedAccessException: 'Access denied for 'C:\Users\user\Desktop'.' – tonga Oct 13 '22 at 17:04
  • 1
    Desktop is a _folder_. You're trying to write to a folder? – gunr2171 Oct 13 '22 at 17:04
  • Show how you build the path. – Etienne de Martel Oct 13 '22 at 17:06

1 Answers1

1

Make sure to validate your path. If your path is a folder, you need to append a filename:

//check if folder exists
if(!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}

//append filename
var filepath = Path.Combine(path, "myfile.txt");

//write file
TextWriter txt = new StreamWriter(filepath);
  
for (int i = 0; i < Movies.Count; i++)
{
   txt.WriteLine(Movies[i].title);
}

txt.Close();

Do not attempt to write directly to a folder, that's probably whats causing the exception. You always need to provide a valid path to a file to write to.

Julian
  • 5,290
  • 1
  • 17
  • 40
  • 1
    You might also want to wrap your code with a try-catch block if you're not certain about the validity of certain paths, depending on your use cases. – Julian Oct 13 '22 at 17:29
  • `Directory.CreateDirectory` is a no-op if the directory already exists, so no need for `Directory.Exists` (and anyway, that'd be a race condition regardless). – Etienne de Martel Oct 24 '22 at 00:26