我无法将字符串写入文件,我不明白出了什么问题。堆栈跟踪:
в System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
в System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
в System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
в System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
в System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
в System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
в VKBot.Program.Main(String[] args) в C:\Development\botdita\Program.cs:строка 648
此块中的代码:
using (StreamReader sr = new StreamReader(reportFile, System.Text.Encoding.Default))
{
text = sr.ReadToEnd();
}
using (StreamWriter sw = new StreamWriter(reportFile, false, System.Text.Encoding.Default))
{
text += String.Format("REPORT из конференции ID{0} от @id{3}({1} {2}): {4}\n", chatID, from.FirstName, from.LastName, senderID, arg);
sw.WriteLine(text);
}
当我尝试使用File.AppendAllText()
它时,它给出了同样的错误:
в System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
в System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
в System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
в System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
в System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
в System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
в System.IO.File.InternalAppendAllText(String path, String contents, Encoding encoding)
в VKBot.Program.Report(String arg) в C:\Development\botdita\Program.cs:строка 635
в VKBot.Program.Command(String Message) в C:\Development\botdita\Program.cs:строка 519
в VKBot.Program.Watcher_NewMessages(VkApi owner, ReadOnlyCollection`1 messages) в C:\Development\botdita\Program.cs:строка 835
в VKBot.Program.<WatchAsync>d__54.MoveNext() в C:\Development\botdita\Program.cs:строка 935
感谢安德鲁的建议。你只需要使用最简单的方法
File.AppendAllText(string filepath, string text);
,你不需要考虑文件是否已经创建,这个命令会为你做一切。