c# - 我收到“该进程无法访问该文件,因为它正被另一个进程使用”错误。有任何想法吗?
问题描述
所以,我在 AppData 中创建了一个文件和一个 txt 文件,我想覆盖 txt。但是当我尝试这样做时,它一直给我这个错误。有任何想法吗?
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string setuppath = (path + "\\");
string nsetuppath = (setuppath + "newx" + "\\");
Directory.CreateDirectory(nsetuppath);
string hedef2 = (nsetuppath + "commands.txt");
File.Create(hedef2);
StreamWriter sw = new StreamWriter(hedef2); ----> This is where the error appears.
sw.WriteLine("Testtest");
解决方案
使用流时只需使用该using
语句。当使用它的代码完成时,using 语句会自动调用对象上的 Dispose。
//path to the file you want to create
string path = @"C:\code\Test.txt";
// Create the file, or overwrite if the file exists.
using (FileStream fs = File.Create(path))
{
byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
有很多操作流的方法,根据您的需要保持简单
推荐阅读
- r - 通过安装较新版本来覆盖 Azure ML 中已安装的 R 包?
- c++ - 如何使用指向结构 c++ 向量的迭代器?
- amazon-s3 - 使用 Python 在 S3 中上传文件时如何动态获取文件名?
- java - jax-ws 重定向 http / https
- android - ViroCore:java.lang.NoClassDefFoundError:解析失败:Lcom/google/vr/ndk/base/GvrLayout;
- java - 在java elasticsearch中获取价格范围在最小值和最大值之间的数据
- php - SQL:无效的参数号:未定义参数
- java - 如果两者都需要在同一类中的每个 @Test 中运行,如何使用多个凭据验证登录功能[在 Maven POM Selenium 项目中]
- python - Sci-kit Learn KNN 用户自定义距离矩阵:实际值与传递值不匹配
- javascript - D3 v5 变焦口吃