-2

我试图指定我应该使用 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 按任意键继续。. .

4

1 回答 1

7

错误消息中说明了最可能的原因:“找不到路径的一部分” - 流编写器不会创建文件夹,只会创建文件。

使用Directory.CreateDirectory和相关函数来确保文件夹存在。

旁注:请使用特殊的 Path.Combine方法来构造路径,而不是手动字符串连接。

于 2013-07-19T07:07:31.583 回答