【发布时间】:2023-01-22 10:48:51
【问题描述】:
这是一个关于如何在读取、修改和写入阶段之间共享相同数据列表的一般编码问题。
我也是 C# 的新手和新手,所以我很挣扎。我期望能够:将 CSV 读入变量 records,修改一条或多条记录,然后将修改后的数据作为新的 CSV 写出,但 using 函数存在范围问题。
下面的代码无法编译,因为 records 超出了旨在修改某些数据的 foreach 循环以及我尝试写入修改后的文件时的范围。
我尝试了各种方法来使 records 成为一个更全局的变量,但它们都失败了,我无法理解。
我什至不确定这是解决问题的最佳方法,因此我们将不胜感激。
private void Btn_Merge_Click(object sender, EventArgs e)
{
// Read the CSV into 'records'
StreamReader reader = new StreamReader(textBox_Shopify.Text);
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<Contact>();
}
// We now need to find the record for a specific person and change it
foreach (Contact customer in records)
{
if (customer.Email == "john.dow@business.com") // Hard-coded while testing
{
string Tags = customer.Tags; // Get the current tags
// If the Lead Marking tag is not already there, add it
if (!Tags.Contains("Send me Lead Marketing"))
{
// If there are tags already there, append a semi-colon separator
if (customer.Tags.Length > 0)
{
customer.Tags += ";";
}
customer.Tags += "Send me Lead Marketing";
MessageBox.Show(customer.Email + " Tags: " + customer.Tags); //Just while I'm testing
}
}
// If the customer is not in the list, add them as a new record
// To do...
}
// We can now write out the modified file
using (var writer = new StreamWriter(@"C:\temp\Output.csv"))
using (var outputCSV = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
outputCSV.WriteRecords(records);
}
}
public class Contact
{
[Name("First Name")] // This 'attribute' allows the class property First_Name to be matched to the header "First Name"
public string First_Name { get; set; }
[Name("Last Name")]
public string Last_Name { get; set; }
public string Email { get; set; }
[Name("Accepts Email Marketing")]
public string Accepts_Email_Marketing { get; set; }
public string Company { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string Province { get; set; }
[Name("Province Code")]
public string Province_Code { get; set; }
public string Country { get; set; }
[Name("Country Code")]
public string Country_Code { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
[Name("Accepts SMS Marketing")]
public string Accepts_SMS_Marketing { get; set; }
[Name("Total Spent")]
public string Total_Spent { get; set; }
[Name("Total Orders")]
public string Total_Orders { get; set; }
public string Tags { get; set; }
public string Note { get; set; }
[Name("Tax Exempt")]
public string Tax_Exempt { get; set; }
}
【问题讨论】: