尝试创建一个try catch异常,如果找不到文件,则加载带有旧文件值的新文件
本文关键字:文件 加载 新文件 找不到 一个 创建 try catch 如果 异常 | 更新日期: 2023-09-27 18:17:40
我有一个try catch异常,如果dict.csv文件不能找到一个消息框,将出现一个新文件,称为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");
}
我认为你最好使用:
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());
}
}