试图创建一个尝试捕获异常,如果无法找到一个文件与旧文件的值的新文件被加载而不是

问题描述:

我有一个try catch异常,如果dict.csv文件不能找到一个messagebox将出现并且将创建一个名为newdict.csv的新文件 - 如何将dict.csv文件的旧值加载到新文件中?试图创建一个尝试捕获异常,如果无法找到一个文件与旧文件的值的新文件被加载而不是

这些值是用户名和密码的列表?

try //checks for existing dict.csv file and reads it for key and value and checks against credentials 
     { 

      var data = File.ReadAllLines(@"C:\Users\Scott\Documents\dict.csv");//Reads all contents of a file and then closes the file once its been read 
      foreach (var login in data) 
      { 
       var parts = login.Split(',');//creates a variable called data and loads it with the dict.csv file 
       Credentials.Add(parts[0].Trim(), parts[1].Trim());//splites the key and value into [0] and [1] and trim removes leading and white space and applies "," 
      } 
     } 
     catch (FileNotFoundException)//How do I load the newdict.csv with values of dict.csv? 
     { 
      MessageBox.Show("dict.csv file does not exist! Creating new file called newdict.csv", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
      using (StreamWriter writer = File.AppendText(@"C:\Users\Scott\Documents\newdict.csv ")) 
      Credentials.Add("bob2", "password");       
      Credentials.Add("user", "pass"); 
     } 
+2

你怎么能来自于不存在的文件加载具有值的文件? – KevinDTimm

+0

如果旧文件不存在,新文件将存在 – Scott

+0

我不确定您是否知道自己想要什么。首先,如果“dict.csv”不存在,并且您想要将不存在的旧文件“dict.csv”的内容加载到“newdict.csv”中,您可以创建一个'newdict.csv'? – t3chb0t

我想你会更好,如果你使用:

string[] newCredentials, data, parts; 
if (!File.Exists(@"C:\Users\Scott\Documents\dict.csv")) 
{ 
    //create .csv file 
    newCredentials = new string[2]; 
    newCredentials[0] = "Bob2,password"; 
    newCredentials[1] = "user,pass"; 
    File.WriteAllLines(@"C:\Users\Scott\Documents\newdict.csv", newCredentials)) 
    Credentials.Add("bob2", "password");       
    Credentials.Add("user", "pass"); 
} 
else 
{ 
    data = File.ReadAllLines(@"C:\Users\Scott\Documents\dict.csv"); 
    foreach(string login in data) 
    { 
     parts = login.Split(','); 
     Credentials.Add(parts[0].Trim(), parts[1].Trim()); 
    } 
} 
+0

嗯,我想保留try catch,但是如何在创建newCredentials后加载新的csv文件? – Scott

+0

@Scott不File.WriteAllLines(字符串路径,字符串[]行)为你工作? – GeMaths

+0

它不起作用!对不起 – Scott