How can I save TXT file in C: directory using C#?

Asked

Viewed 725 times

3

I’m trying to make a small data scrolling program and I want it to save a file. txt that stores the scrolls, so that it can be read later. The program is practically whole ready, all functionalities working, but when I try to select the directory where the . txt will be saved as the C:\ he won’t let me use it, probably because of permission issues.

As I will make an installer of this program to distribute it on the internet, I need to save it in a directory that is standard on any PC, and so I thought the C:\ would be ideal. I wonder if you could lend me a hand?

  • Explain your problem better, put the code you are using for this. But I already assume that C: is the opposite of ideal. And you probably have permission issues anyway.

  • Are you trying to save directly in C:? Or in a subfolder? What is the mistake when you try to save? Post the code so we understand what you’re doing.

  • Runs it as an administrator, you probably don’t have enough rights.

2 answers

1

System.IO.Path.GetTempPath() is just a wrapper for a native call to GetTempPath (..) in Kernel32 .

Take a look link

1


If you are trying to save to a folder within C it may not exist,s and that is the case, you can check if it exists and create it if the case:

var dirPath = @"C:\Temp\";
var filePath = dirPath + "arquivo.extensao";

// Verifica se o diretório não existe e cria 
if (!Directory.Exists(dirPath))
    Directory.CreateDirectory(dirPath);

// Da mesma maneira para o arquivo
if (!File.Exists(filePath))
    using (File.Create(filePath)) { }
  • 1

    This is terrible, halfway through the situation can change and you have a race condition.

  • Dude, you don’t have to create another answer. You can edit your previous one.

  • What do you mean @bigown? Can you explain better? @jbueno I’ll remember the next one. Thanks

  • If you have questions, ask a question.

  • I don’t see the need for a question about, it would only be interesting if you explained why this code could cause a race condition. This is a way to check if the file I will use actually exists before trying to do anything. It is not right that thinking?

  • Thank you very much personally, especially to Pedro Camara! Everything worked out right here :)

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.