我试图使用StreamWriter指定存储创建文件的位置:
string getCurrentPath = Environment.CurrentDirectory;
StreamWriter writeFile = new StreamWriter(@"" +getCurrentPath + "\\NDependProject\\OceanAPIDependencies.xml");
writeFile.Close();
我收到此错误消息:
Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path 'D:\Project_Summer\ExtensionDirectoryTraversal\ExtensionDirectoryTr aversal\bin\Debug\NDependProject\OceanAPIDependencies.xml'. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, I nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions o ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolea n useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean che ckHost) at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encodin g, Int32 bufferSize, Boolean checkHost) at System.IO.StreamWriter..ctor(String path) at ExtensionDirectoryTraversal.Program.Main(String[] args) in d:\Project_Summ er\ExtensionDirectoryTraversal\ExtensionDirectoryTraversal\Program.cs:line
15 按任意键继续 。 。
答案 0 :(得分:6)
最有可能的原因在错误消息中说明:“找不到路径的一部分” - 流编写器不会创建文件夹,只会创建文件。
使用Directory.CreateDirectory及相关功能确保文件夹存在。
附注:请使用特殊的Path.Combine方法来构造路径而不是手动字符串连接。