我寫下面的代碼來重新格式化源文本文件(columns_original)並寫入輸出文件(output.ctl)。它正在工作,但我應該做的是,在由以下代碼創建的輸出文件的最後一行中,文件末尾有一個「,」,我想將其更改爲「。」。我應該在哪個部分嵌入此代碼?我說這個在最後,但我得到一個錯誤「類型‘System.IO.IOException’未處理的異常出現在mscorlib.dll輸出文件正被另一個程序使用」如何用「」替換「,」。「在文件的最後一行?
// I am trying to replace "," with "." at the last line of the text I created above and I created below code.
// I am trying to replace "," with ")" at the last line of the text I created above and
using (FileStream aFile2 = new FileStream(path, FileMode.Append, FileAccess.Write))
using (StreamWriter sw2 = new StreamWriter(aFile2))
{
var lastLine = File.ReadLines(path).Last();
lastLine = lastLine.Replace(",", ".");
sw2.WriteLine(lastLine);
}
MCVE:
// I ADDED ABOVE CODE TO BELOW WORKING PART AND I AM GETTING ERROR MENTIONED IN THE POST
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CTL_CMD_Creator
{
class Program
{
static void Main(string[] args)
{
string ColChangable1 = "VARCHAR2";
string ColChangable2 = "CHAR";
string ColChangable3 = "NUMBER";
string ColChangable4 = "DATE";
string path = @"C:\Users\***\Desktop\output.ctl";
StreamReader reader = File.OpenText(@"C:\Users\***\Desktop\Columns_Original.txt");
string line;
using (FileStream aFile = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(aFile))
{
while ((line = reader.ReadLine()) != null)
{
string[] tokens = line.Split(new char[] { ' ', '\t', '(', ')', ',' }, StringSplitOptions.RemoveEmptyEntries);
if (tokens[1].Equals(ColChangable1) || tokens[1].Equals(ColChangable2))
{
sw.WriteLine(tokens[0] + "\t" + "\"TRIM(:" + tokens[0] + ")\",");
}
else if (tokens[1].Equals(ColChangable3))
{
sw.WriteLine(tokens[0] + "\t" + ",");
}
else if (tokens[1].Equals(ColChangable4))
{
sw.WriteLine(tokens[0] + "\t" + "DATE" + ",");
}
}
}
}
}
}
}
你能張貼在dotnetfiddle? – aloisdg
很難理解你在哪裏調用替換函數以及失敗的地方。 –
您可能會重新考慮您的主循環。例如,您可以只執行一個簡單的寫操作來寫入除「,」之外的行,然後在下一次迭代時僅執行簡單的WriteLine(「,」),並且在退出循環之後 - 執行額外的WriteLine(「。」) –