尝试创建try catch异常,如果找不到文件,则加载具有旧文件值的新文件,而不是 [英] trying to create a try catch exception where if a file can't be found a new file with values of the old file is loaded instead
本文介绍了尝试创建try catch异常,如果找不到文件,则加载具有旧文件值的新文件,而不是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个try catch异常,如果找不到dict.csv文件,则会出现一个消息框,并且将创建一个名为newdict.csv的新文件-如何将dict.csv文件的旧值加载到新文件?
I have a try catch exception where if the dict.csv file cant e found a messagebox will appear and a new file will be created called newdict.csv - How do I load the old value of the dict.csv file into the new file?
这些值是用户名和密码的列表吗?
The values being a list of usernames and passwords?
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");
}
推荐答案
如果您使用以下方法,我认为您会更好:
I think you would be better off if you used:
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());
}
}
这篇关于尝试创建try catch异常,如果找不到文件,则加载具有旧文件值的新文件,而不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文