在c#和Unity中创建和编写txt文件时,它只创建该文件,不使用该文件
我正在制作一个以c#为主要编程语言的统一游戏。我尝试创建一个新的save.txt和autosave.txt,如果它在app文件夹中还不存在的话。它可以创建它,但不能正常工作。这是我的密码: 创建和写入新存储:在c#和Unity中创建和编写txt文件时,它只创建该文件,不使用该文件,c#,file,unity3d,save,C#,File,Unity3d,Save,我正在制作一个以c#为主要编程语言的统一游戏。我尝试创建一个新的save.txt和autosave.txt,如果它在app文件夹中还不存在的话。它可以创建它,但不能正常工作。这是我的密码: 创建和写入新存储: void Start () { if(!File.Exists(Application.dataPath.ToString() + "/Save.txt")) { File.CreateText(Application.dataPath.ToStri
void Start () {
if(!File.Exists(Application.dataPath.ToString() + "/Save.txt"))
{
File.CreateText(Application.dataPath.ToString() + @"/Save.txt");
saveFilePath = Application.dataPath.ToString() + @"/Save.txt";
TextWriter writer = new StreamWriter(saveFilePath, false);
writer.WriteLine("10:21:59", "13 / 06 / 2017", "1", "1", "-21", "20000", "100", "500", "50", "20", "500","2","1","1","5000", "10");
writer.Close();
}
if(!File.Exists(Application.dataPath.ToString() + "/AutoSave.txt"))
{
File.CreateText(Application.dataPath.ToString() + @"/Autosave.txt");
saveFilePath = Application.dataPath.ToString() + @"/Autosave.txt";
TextWriter writer = new StreamWriter(saveFilePath, false);
writer.WriteLine("00:00:00", "01 / 01 / 2017", "1", "1", "-21", "20000", "100", "500", "50", "20", "500", "2", "1", "1", "5000", "10");
writer.Close();
}
}
下面是我编写的一个现存的.txt代码:
public void OnSaveGame()
{
saveFilePath = Application.dataPath.ToString() + @"/Save.txt";
isNewGame = false;
TextWriter writer = new StreamWriter(saveFilePath, false);
theTime = System.DateTime.Now.ToString("hh:mm:ss"); theDate = System.DateTime.Now.ToString("dd/MM/yyyy");
string ZeroPart = theTime + "," + theDate + ",";
string FirstPart = income;
writer.WriteLine(ZeroPart + FirstPart);
writer.Close();
SavingPanel.SetActive(true);
Invoke("WaitTime",2);
}
我不知道我做错了什么。
另外,在unity中,如果有帮助,当我运行它时,它会说“IOException:在路径C:*\Assets\Save.txt上共享冲突”
File.CreateText返回StreamWriter对象。由于您没有使用此对象(或在创建文件的新写入程序之前没有处理它),因此会引发异常,因为多个对象具有/想要对该文件的写访问权限
请了解有关IDisposable和“using”语句的更多信息。不要创建新的StreamWriter,而是尝试使用
File.CreateText()返回的StreamWriter。
虽然@b00n和@martennis的答案都有一些道理,但它们有点欠缺。一旦StreamWriter对象创建了文件,仅仅关闭流不会解除它对该文件的锁定。因此,当您创建一个新的StreamWriter来访问该文件时,它会抛出IOException,因为您的新流无法获得访问权限,因为它仍然被旧流锁定。关闭流并对其进行处理将确保流能够进行所需的适当清理,以便释放文件以供后续读取。我强烈建议阅读MSDN上的文件API文档,以便更好地了解它的功能以及如何使用它
编辑:确保清理StreamWriter对象的一种方法是使用@O.Matei提到的using语句。这将是以下几点:
using(TextWriter writer = new StreamWriter(saveFilePath, false))
{
theTime = System.DateTime.Now.ToString("hh:mm:ss"); theDate = System.DateTime.Now.ToString("dd/MM/yyyy");
string ZeroPart = theTime + "," + theDate + ",";
string FirstPart = income;
writer.WriteLine(ZeroPart + FirstPart);
writer.Close();
}
using语句基本上相当于try-catch-finally,在finally语句中调用writer.Dispose(),以确保即使发生异常,所使用的资源也已正确清理