2015-11-04 196 views
-1

有人能告诉我为什么我在下面的代码中有这个错误吗? beucase它使用由另一个procces无法打开文件c#

的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

还要确保您有权限访问该文件。 –

+0

我没有打开任何文本编辑器。 –

回答

-1

解决方案:您需要找到一个程序来打开此文件并杀死它或重新加载操作系统。

我建议你要改变 “_class =属性oldValue” 的 “_class = NEWVALUE” 使用_class这样

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) 
      { 

      } 
     } 
+0

我的属性文件在一行上有一个未知数的'='(大于或等于一)例如:user = Xg245 = asFS5 = 43(我将之前的文本隐藏在文件中)。 –