4

I want to be able to write a string to a text file on any computer. For example

string line = "Sample text to write"
File.WriteAllText(@"C:\Users\Rolex James\Documents\sample.txt" , line);

On another system this path would be different, is there a way of writing it such that you don't have to modify the path to suit each system you want to run it on?

user247702
  • 23,641
  • 15
  • 110
  • 157
Babalola Rotimi
  • 319
  • 5
  • 10
  • possible duplicate of [How can I access the "Documents and Settings" folder?](http://stackoverflow.com/questions/16752534/how-can-i-access-the-documents-and-settings-folder) – Wyatt Earp Jun 16 '15 at 16:01

1 Answers1

8

It depends on where you want to write it, which isn't completely clear by your question. If you're always looking for the current user's documents, then you should look at the System.Environment.GetFolderPath method and the System.Environment.SpecialFolder.MyDocuments enumeration value in particular. When that executes, it will give you the path to the current user's documents directory, which will vary from user to user and computer to computer.

Tim
  • 14,999
  • 1
  • 45
  • 68
  • I get an 'access to the path is denied' error. How do I fix this? – Babalola Rotimi Jun 16 '15 at 15:58
  • You're going to have to give us a whole lot of extra information then. What type of app is it, how is it running, etc. Also update your post to show the code you're running now (or create a new post, since this is almost certainly a different issue) – Tim Jun 16 '15 at 16:00
  • It worked. I was writing to a directory instead of a file. Thanks – Babalola Rotimi Jun 16 '15 at 16:02