字符串文件路径不起作用c#

时间:2012-12-30 23:22:21

标签: c# string path .net

好吧,我花了大量时间试图解决我读过的帖子所说的简单修复。

我想在我的文档中写一个文件,这是我的代码。

        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();

用户名在哪里。我收到以下错误

“mscorlib.ni.dll中出现'System.IO.DirectoryNotFoundException'类型的第一次机会异常。在mscorlib.ni.dll中发生了'System.IO.DirectoryNotFoundException'类型的异常,但未处理在用户代码“

我正在使用Visual Studio Express进行Windows Phone开发。

如果有人能够指出我做错了什么,我将不胜感激。

感谢。

3 个答案:

答案 0 :(得分:2)

我假设您在发布时使用了字符串。如果是这种情况,您应该使用SpecialFolder Enum。

var st = string.format(@"{0}\Sample1.txt", 
             Environment.GetFolderPath(Environment.SpecialFolder.Personal));

答案 1 :(得分:1)

您应该利用Environment.SpecialFolder枚举并使用Path.Combine(...)创建路径:

var path = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.Personal),
    "Sample1.txt");

using (var sw = new StreamWriter(path))
{
    sw.WriteLine(Convert.ToString(Sample1[0]));
}

此外,StreamWriter应放在using声明中,因为它是一次性的。

答案 2 :(得分:0)

要使用MyDocuments:

    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

这将返回主机上MyDocuments的路径。

您可以在MSDN上查看SpecialFolders列表:http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx

编辑:我刚刚注意到你正在为Windows Phone开发。阅读MSDN上的其他SpecialFolders。

相关问题