Unity dll文件删除文件并编写异常

时间:2015-07-03 04:11:26

标签: c# unity3d ioexception

我正在尝试使用文件来读取我的数据,这是我写的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 ()

1 个答案:

答案 0 :(得分:0)

试试这样:

// 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.Close