创建后无法立即写入文件
在以下代码中:
if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat"))
{
File.AppendAllText(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", temp);
}
else
{
File.Create(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat");
File.SetAttributes(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", FileAttributes.Hidden);
File.AppendAllText(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", temp);
}
由于某种原因,第一次运行此代码时,它会很好地创建文件,但不会写入文件,直到我退出应用程序并重新运行它时才会写入文件。第二次、第三次等等运行都很好,只是最初的部分有点奇怪。有什么想法吗?文件名和目录是随机的,因为我只是在测试某些内容,因此如果您正在测试某些内容,您应该能够将它们更改为您想要的任何内容。提前致谢
In the following code:
if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat"))
{
File.AppendAllText(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", temp);
}
else
{
File.Create(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat");
File.SetAttributes(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", FileAttributes.Hidden);
File.AppendAllText(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", temp);
}
for some reason, the first time this code is run, it creates the file just fine, but does not write to it, and it will not until i exit the app, and re-run it. the 2nd, 3rd, and so on runs work just fine, its just the initial that's screwy. any ideas? file names and directories are random since i was just testing something so you should be able to change those to whatever you want if you're testing something. Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该将 .Close() 放在 File.Create 之后
阅读更多信息 MSDN File.Create
或者您可以执行此操作
,请访问 MSDN 文件.WriteAllText
You should put .Close() after File.Create
Read more at MSDN File.Create
or You can do this
Read more at MSDN File.WriteAllText
File.Create
正在将您的流返回到文件,您可能希望在尝试再次重新打开它之前关闭它。File.Create
is returning you stream to file you might want to close it before you try to reopen it again.File.AppendAllText() 将创建该文件(如果该文件尚不存在),因此您可以这样做:
看看是否有帮助:)
File.AppendAllText() will create the file if it does not already exist, so you could just do:
See if that helps :)
跳过创建文件,如果文件不存在,AppendAllText 方法仍然会创建它。
我猜测 file.create 可能会打开文件锁或文件句柄。
Skip creating the file, the AppendAllText method creates it anyway if it's not there.
I'm guessing the file.create might leave a file lock or file handle open.