Reputation: 21
Okay I have spent an inordinate amount of time trying to solve what the posts i've read say is a simple fix.
I want to write to a file in my documents and here is my code.
string st = @"C:\Users\<NAME>\Documents\Sample1.txt";
System.IO.StreamWriter file = new System.IO.StreamWriter(st);
file.WriteLine(Convert.ToString(Sample1[0]));
file.Close();
Where is the user name. I am getting the following error
"A first chance exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.ni.dll. An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.ni.dll but was not handled in user code"
I am using Visual Studio Express for Windows Phone Development.
If anyone can point out what i am doing wrong i would be grateful.
Thanks.
Upvotes: 2
Views: 5820
Reputation: 3574
To get MyDocuments use:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
This will return the path to MyDocuments on the host computer.
You can see a list of SpecialFolders on MSDN: http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx
EDIT: I just noticed you were developing for Windows Phone. Read up on the other SpecialFolders on MSDN.
Upvotes: 0
Reputation: 32515
You should take advantage of the Environment.SpecialFolder
enumeration and use Path.Combine(...)
to create a path:
var path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Personal),
"Sample1.txt");
using (var sw = new StreamWriter(path))
{
sw.WriteLine(Convert.ToString(Sample1[0]));
}
Also, StreamWriter
should be placed within a using
statement since it is disposable.
Upvotes: 1
Reputation: 25445
I assuming you're using the string as you've posted it. If thats the case you should use the SpecialFolder Enum instead.
var st = string.format(@"{0}\Sample1.txt",
Environment.GetFolderPath(Environment.SpecialFolder.Personal));
Upvotes: 2