【问题标题】:Path changing when calling streamwriter? [closed]调用streamwriter时路径改变? [关闭]
【发布时间】:2013-01-19 23:49:35
【问题描述】:

所以,我有以下三行c#代码:

string pageAnnotationTextFilePath = currentPagePath.Substring(0, currentPagePath.Length-4) + ".txt";
print (pageAnnotationTextFilePath);
StreamWriter sw = new StreamWriter(pageAnnotationTextFilePath, false);

当我运行它时,我首先收到以下打印消息,表示名为 pageAnnotationTextFilePath 的字符串的值:

file://C:/Users/USER/Desktop/Accessible/Assets/IO/Books/A community of learners/king/pages/page1.txt

这是正确的,也应该如此。但是,程序中的下一行给了我下面的错误。似乎正在发生的事情是我的路径正在被 StreamWriter 初始化类改变——导致项目的位置被附加到我提供的路径的第一部分。为什么要这样做,为什么要这样做?我在堆栈跟踪中提到的路径就在顶部,这里:

DirectoryNotFoundException: Could not find a part of the path "C:\Users\USER\Desktop\Accessible\file:\C:\Users\USER\Desktop\Accessible\Assets\IO\Books\A community of learners\king\pages\page1.txt".
System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options)
System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share)
(wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)
System.IO.StreamWriter..ctor (System.String path, Boolean append, System.Text.Encoding encoding, Int32 bufferSize)
System.IO.StreamWriter..ctor (System.String path, Boolean append)
(wrapper remoting-invoke-with-check) System.IO.StreamWriter:.ctor (string,bool)
AnnotationIO+<SaveAllObjectDataToTextFile>c__Iterator0.MoveNext () (at Assets/AnnotationIO.cs:27)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
<SaveDataToBooksFolder>c__Iterator6:MoveNext() (at Assets/Scripts/GUI/WizardAnnotationGUI.cs:81)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
<AutoSave>c__Iterator5:MoveNext() (at Assets/Scripts/GUI/WizardAnnotationGUI.cs:71)

感谢您的专业知识!

【问题讨论】:

  • currentPagePath 的值是什么?

标签: c# string path directory streamwriter


【解决方案1】:

这是一个提示

'找不到部分路径“C:\Users\USER\Desktop\Accessible\file:\C:\Users\USER\Desktop\Accessible\Assets\IO\Books\A community of learners\king \pages\page1.txt"'

并注意您的打印输出是

'file://C:/Users/USER/Desktop/Accessible/Assets/IO/Books/A community of learners/king/pages/page1.txt'

因此,您正在将此字符串提供给 StreamWriter。 StreamWriter 正在获取此字符串并将其用作相对路径。您的工作目录必须是:

'C:\Users\USER\Desktop\Accessible\'

两者正在相互附加。长话短说,你必须去掉“file://”

【讨论】:

  • 啊,这完全有道理。谢谢。我想我很好奇它为什么会这样做——但可惜的是,比我更伟大的头脑已经猜到了这就是方式。
猜你喜欢
  • 2013-12-19
  • 1970-01-01
  • 2019-12-11
  • 1970-01-01
  • 2012-08-18
  • 2022-06-14
  • 2013-05-06
  • 2017-11-27
  • 1970-01-01
相关资源
最近更新 更多