有人可以告诉我为什么我在下面的代码中出现此错误?
procces无法访问文件" ..." beucase它是由另一个procces使用。
我关闭了第一个StreamReader
,之后,当我初始化StreamWriter
时,它就崩溃了。
private static void removeSetting(string _class)
{
try
{
string[] allSettings = new string[20];
int iSettings = 0;
using (StreamReader FILE_READER = new StreamReader("DATA.properties"))
{
string line = FILE_READER.ReadLine();
while (line != null)
{
if (!line.Equals(""))
{
allSettings[iSettings] = line;
iSettings++;
}
line = FILE_READER.ReadLine();
}
}
using (StreamWriter FILE_WRITER = new StreamWriter("DATA.properties", false))
{
for (int i = 0; i <= iSettings; i++)
{
if (!allSettings[i].Split('=')[0].Equals(_class))
{
FILE_WRITER.WriteLine('\n' + allSettings[i] + '\n');
//i--;
}
}
}
}
catch (Exception ex)
{
}
}
public static void saveSetting(string _class, string value)
{
removeSetting(_class);
try
{
StreamWriter FILE_WRITER = new StreamWriter("DATA.properties", true);
FILE_WRITER.WriteLine( _class.ToString() +'='+ value);
FILE_WRITER.Close();
}
catch (Exception ex)
{
}
}
答案 0 :(得分:-1)
解决方案:您需要找到一个打开此文件并将其终止或重新加载操作系统的程序。
我建议您使用_class这样的“_class = newValue”更改“_class = oldValue”
oldText:
狗=锁
猫=鲍勃
使用saveSetting(dog,fork)
newText:
猫=鲍勃
狗=叉
你可以使用这种方法
private static void removeSetting(string _class,string value)
{
try
{
//read all lines from file
string[] allSettings = File.ReadAllLines("DATA.properties");
//divide string on string[] by '='
List<List<string>> strings = allSettings.Select(x => x.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries).ToList()).ToList();
//find all lines where first element equals _class
List<List<string>> result = strings.Where(x => x.First().Equals(_class)).Select(x=>new List<string>{_class, value}).ToList();
// convert string[] => string
string[] secondResult = result.Select(x => String.Join("=",x.ToArray())).ToArray();
List<List<string>> otherResult = strings.Where(x => !x.First().Equals(_class)).Select(x => x).ToList();
string[] firstResult = otherResult.Select(x => String.Join("=", x.ToArray())).ToArray();
//wrtie all lines in file
File.WriteAllLines("DATA.properties",firstResult);
File.AppendAllLines("DATA.properties", secondResult);
}
catch (Exception ex)
{
}
}