Unity dll文件删除文件并写入异常
本文关键字:文件 异常 删除 dll Unity | 更新日期: 2023-09-27 18:00:51
我正在尝试使用文件来读写我的数据,这是我在dll文件中的代码,我写了
public static void WriteFile(string fileName, string writeline)
{
bool checker = false;
#if UNITY_WEBPLAYER
checker = true;
#endif
if (checker)
{
return;
}
string pathname = Application.persistentDataPath + "/" + fileName;
if (File.Exists(pathname))
{
Debug.Log("userdata already exists.");
File.Delete(pathname);
}
// Create the file.
using (FileStream fs = File.Create(pathname))
{
Byte[] info = new UTF8Encoding(true).GetBytes(writeline);
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}
当我试图写文件,而这个文件存在时,这个异常会抛出,但若我再次写,并没有异常。我想第一次调用此函数时,文件已成功删除。但我需要解决第一次写入文件的异常。
IOException: Sharing violation on path C:/Users/player/AppData/LocalLow/DefaultCompany/Testing Unity Project/UserInfo.txt
System.IO.File.Delete (System.String path) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.IO/File.cs:179)
FileControl.WriteFile (System.String fileName, System.String writeline)
Test+<LoginClientTest>d__0.MoveNext ()
这样尝试:
// Exclude File.DeleteCode
using (FileStream fs = File.Create(pathname))
{
Byte[] info = new UTF8Encoding(true).GetBytes(writeline);
// Add some information to the file.
fs.Write(info, 0, info.Length);
fs.Close(); // Close the stream
}
或者尝试使用StreamWriter
写入文件。
FileStream。关闭