2

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.

3
  • 2
    DirectoryNotFoundException ... does the directory exist on the phone? Commented Dec 30, 2012 at 23:24
  • Debug your code, figure out which directory or file is not found in your path string. Commented Dec 30, 2012 at 23:27
  • 1
    You are using desktop Windows path conventions on a phone. That will not work, the places where you can store a file on a consumer device are very limited. Isolated storage is the rule. All the answers you got are tripped up by that, you didn't make it clear what phone version you are using. Commented Dec 30, 2012 at 23:45

3 Answers 3

2

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));
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.