抛出NotSupportedException

时间:2014-05-24 07:47:43

标签: c# file-io

我正在使用C#创建一个函数来将数据写入文件系统中的文件,如果文件不存在,则重新创建并重复函数。

只是编写数据的第一种方法是有效的。但是第二种方法,如果文件不存在而程序必须首先创建它,则不起作用。它创建文件但同时在Visual Studio中向我抛出一个异常

  

System.NotSupportedException未处理

我正在使用MSDN所拥有的完整代码副本。

http://msdn.microsoft.com/en-us/library/d62kzs03(v=vs.110).aspx

以下是我在第二个代码块中使用的内容

// Create file!
using (FileStream fs = File.Create(file))
{
   Byte[] info = new UTF8Encoding(true).GetBytes("some text in the file.");
   // Add some information to the file.
   fs.Write(info, 0, info.Length);
}
// Continue again with the request. 
createFile(file);

方法声明(如果需要)为

private static void createFile (string fileName) {
   string file = "C:\\Users\\AfzaalAhmad\\Documents\\" + fileName + ".txt";
   /* two methods here */
}

图像如下:(注意文件路径中没有错误)我使用过

Console.Write(file); // to get the path, and its OK!

见下图↓

enter image description here

请注意,它确实在Documents文件夹中创建了该文件。但抛出这个例外。我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

请注意例外报告中的详细信息:"不支持给定路径的格式。"

另请查看变量file的内容 - 它似乎是@" C:\ Users \ AfzaalAhmad \ Documents \ C:\ Users ..." - 即它包含两次路径。

因此即使操作系统可能以某种方式管理创建某种文件,文件名也不包含有效值。

[edit] createFile(file);Console.Write(file);都取值@" C:\ Users \ AfzaalAhmad \ Documents \ dsg b.txt"但是你的方法createFile然后第二次添加路径。将其更改为:

private static void createFile (string file) {
   /* two methods here */
}

答案 1 :(得分:0)

请准确查看异常消息和文件变量的值!有你的错误!

相关问题