在編碼中,我想替換 CSV 的列值。但是,它不能替換 CSV 中的值。
CSV 檔案:
"Name","Age"
"michael","16"
"miko","15"
"Tom","24"
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string text = File.ReadAllText(@"C:\test.csv");
TestDataModel users = new TestDataModel();
text = users.Name.Replace("m", "n");
File.WriteAllText(@"C:\test.csv", text);
}
public class TestDataModel
{
public string Name { get; set; }
public int Age { get; set; }
}
}
}
uj5u.com熱心網友回復:
嘗試這個
public static void Replace()
{
string text = File.ReadAllText(@"C:\test.csv");
string _text = text.Replace("m", "n");
File.WriteAllText(@"C:\New_test.csv", _text);
}
uj5u.com熱心網友回復:
您提供的代碼中有很多誤解,您的問題的一些解決方案可能不太友好。特別是當它們不是“全球”解決方案時。對于您的情況,我嘗試在注釋中解釋部分代碼
using System.Text.RegularExpressions;
var csvFilePath = @"C:\test.csv";
// Split csv file into lines instead of raw text.
string[] csvText = File.ReadAllLines(csvFilePath);
var models = new List<TestDataModel>();
// Regex that matches your CSV file.
// Explained here: https://regex101.com/r/t589CW/1
var csvRegex = new Regex("\"(.*)\",\"(.*)\"");
for (int i = 0; i < csvText.Length; i )
{
// Skip headers of file.
// That is: "Name","Age"
if (i == 0)
{
continue;
}
// Check for potential white spaces at the end of the file.
if (string.IsNullOrWhiteSpace(csvText[i]))
{
continue;
}
models.Add(new TestDataModel
{
// Getting a name from regex group match.
Name = csvRegex.Match(csvText[i]).Groups[1].Value,
// Getting an age from regex group and parse it into integer.
Age = int.Parse(csvRegex.Match(csvText[i]).Groups[2].Value),
});
}
// Creating headers for altered CSV.
string alteredCsv = "\"Name\",\"Age\"\n";
// Loop through your models to modify them as you wish and add csv text in correct format.
foreach (var testDataModel in models)
{
testDataModel.Name = testDataModel.Name.Replace('m', 'n');
alteredCsv = $"\"{testDataModel.Name}\",\"{testDataModel.Age}\"\n";
}
var outputFilePath = @"C:\test2.csv";
File.WriteAllText(outputFilePath, alteredCsv);
public class TestDataModel
{
public string Name { get; set; }
public int Age { get; set; }
}
但是,此答案包含許多您可能想要熟悉的主題,例如:
- C#中的正則運算式/正則運算式
- 資料序列化/反序列化
- 使用 Linq
- 字串模板
- 輸入/輸出操作
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/376375.html
標籤:C#
上一篇:從xml檔案中獲取所有屬性c#
