调用streamwriter时更改路径

本文关键字:路径 streamwriter 调用 | 更新日期: 2023-09-27 17:57:32

因此,我有以下三行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)

感谢您的专业知识!

调用streamwriter时更改路径

这是一个提示

'找不到路径"C:''Users''USER''Desktop''Accessible''file:''C:''Users''USER''Deskt''Accessible''Assets''IO''Books''a community of learners ''king''pages''page1.txt"的一部分'

注意你的打印结果是

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

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

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

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