C# 尝试创建一个try-catch异常,如果文件可以';找不到具有旧文件值的新文件
我有一个try-catch异常,如果无法找到dict.csv文件,将出现一个消息框,并创建一个名为newdict.csv的新文件-如何将dict.csv文件的旧值加载到新文件中 这些值是用户名和密码的列表吗C# 尝试创建一个try-catch异常,如果文件可以';找不到具有旧文件值的新文件,c#,csv,C#,Csv,我有一个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.R
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());
}
}
如何从一个不存在的文件中加载一个具有值的文件?如果旧文件不存在,那么新文件将存在。我不确定您是否知道自己想要什么。首先,如果
dict.csv
不存在,您将创建一个newdict.csv
,然后您希望将不存在的旧文件dict.csv
的内容加载到newdict.csv
中?我希望保留try-catch,但是,在创建新的csv文件后,我如何使用新凭据加载该文件?@Scott没有文件。WriteAllines(字符串路径,字符串[]行)适用于您?我如何将凭据添加到newdict文件@GeMathsIf如果创建文件“newdict”,则必须使用file.AppendAllLines或file.WriteAllLines,这两个行都需要newdict.csv的路径以及要包含的任何行,例如“user,pass”,这是一行。如果您看到我第一次作为aswer发布的代码,我会将这两行都包含在一个字符串数组中,然后将其作为参数传递给File.writeAllines方法。