3 回答

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超7個(gè)贊
編輯 請(qǐng)嘗試此假設(shè)其空格分隔。
它在我的 VS2017 上工作,請(qǐng)?jiān)陧敳刻砑?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;
}
}
運(yùn)行代碼后我得到了這個(gè)。
Id Code File_Number Suffix Check_Number Check_Date
047 STRINGTOENTER 7699 01 99999 11/11/2012
1 -6.15
請(qǐng)讓我知道這可不可以幫你。

TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
假設(shè)每個(gè)文件都有正確的制表符分隔(考慮到問題質(zhì)量,這是一個(gè)很大的假設(shè))
// 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);
}
}
注意:您可能應(yīng)該使用 CSV 解析器來執(zhí)行此操作,這僅用于學(xué)術(shù)目的并且完全未經(jīng)測(cè)試

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
我想根據(jù)您的輸入展示我想要的解決方案。令人驚奇的是,一段簡(jiǎn)單的代碼可以幫助解決更大、更復(fù)雜的問題。再次感謝!
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 關(guān)注
- 197 瀏覽
添加回答
舉報(bào)