3 回答

TA貢獻1798條經驗 獲得超7個贊
編輯 請嘗試此假設其空格分隔。
它在我的 VS2017 上工作,請在頂部添加 using 語句,如下所示。
using System.Text.RegularExpressions
public static void AddAStringtoAllTextFiles()
{
try
{
string path = @"C:\Users\ur\Desktop\TestFiles\";
var fileEntries = Directory.GetFiles(path);
int indexPosition2InsertData=1;
foreach (var entry in fileEntries)
{
var lines = File.ReadAllLines(entry);
for (var index = 1; index < lines.Length; index++) //starting from first row, leaving the header
{
var split= Regex.Split(lines[index].Trim(), @"\s{1,}"); //reading the line with space(s)
if(split.Length==5) //edited //checking if the row is not blank
{
var list = split.ToList(); //convert to list to insert
list.Insert(indexPosition2InsertData, "STRINGTOENTER"); //inserting at the index 1
lines[index] = string.Join("\t", list);
}
}
File.WriteAllLines(entry, lines);
}
}
catch (Exception e)
{
throw e;
}
}
運行代碼后我得到了這個。
Id Code File_Number Suffix Check_Number Check_Date
047 STRINGTOENTER 7699 01 99999 11/11/2012
1 -6.15
請讓我知道這可不可以幫你。

TA貢獻1890條經驗 獲得超9個贊
假設每個文件都有正確的制表符分隔(考慮到問題質量,這是一個很大的假設)
// Get the files
var fileEntries = Directory.GetFiles(path);
// iterate through each file name
foreach (var entry in fileEntries)
{
// Load the File into the lines array
var lines = File.ReadAllLines(entry);
// Iterate over each line
if(lines.Length >1)
{
// Split the lines by tab
var split = lines[1].Split('\t');
// your code should be at array index 1
split[1] = "STRINGTOENTER";
// write the whole line back
lines[1] = string.Join("\t", split);
// write the file
File.WriteAllLines(entry, lines);
}
}
注意:您可能應該使用 CSV 解析器來執行此操作,這僅用于學術目的并且完全未經測試

TA貢獻1818條經驗 獲得超3個贊
我想根據您的輸入展示我想要的解決方案。令人驚奇的是,一段簡單的代碼可以幫助解決更大、更復雜的問題。再次感謝!
public static void AddClientCodetoAllTextFiles(string update_batch_with_clientcode, string batchfilepathtobeupdated)
{
try
{
var fileEntries = Directory.GetFiles(@batchfilepathtobeupdated.Trim());
foreach (var entry in fileEntries)
{
var lines = File.ReadAllLines(entry);
if (lines.Length > 1)
{
for (int i = 1; i < lines.Length - 1; i++)
{
var split = lines[i].Split('\t');
split[1] = update_batch_with_clientcode.Trim();
lines[i] = string.Join("\t", split);
File.WriteAllLines(entry, lines);
}
}
}
}
catch (Exception e)
{
throw e;
}
}
- 3 回答
- 0 關注
- 184 瀏覽
添加回答
舉報