使用StreamWriter存储在特定路径中

本文关键字:路径 StreamWriter 存储 使用 | 更新日期: 2023-09-27 18:23:57

我正在尝试使用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按任意键继续。

使用StreamWriter存储在特定路径中

最可能的原因在错误消息中说明:"找不到路径的一部分"-流写入程序不会创建文件夹,只会创建文件。

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

附带说明:请使用特殊的Path.Combine方法来构造路径,而不是手动串接。