如何更换","用"。"在文件的结尾?

时间:2017-01-03 12:17:04

标签: c# replace filestream

我在下面写了代码来重新格式化源文本文件(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" + ",");
                    }                        
                }
            }                
        }
    }
}
}

4 个答案:

答案 0 :(得分:3)

使用reader.EndOfStream检查它是否为文件结束。

        while ((line = reader.ReadLine()) != null)
        {

            string[] tokens = line.Split(new char[] { ' ', '\t', '(', ')', ',' }, StringSplitOptions.RemoveEmptyEntries);
            string line;

            if (tokens[1].Equals(ColChangable1) || tokens[1].Equals(ColChangable2))
            {
                line = tokens[0] + "\t" + "\"TRIM(:" + tokens[0] + ")";
            }

            else if (tokens[1].Equals(ColChangable3))
            {
                line = tokens[0] + "\t";
            }
            else if (tokens[1].Equals(ColChangable4))
            {
                line = tokens[0] + "\t" + "DATE";
            }

            line += reader.EndOfStream ? "." : ",";

            sw.WriteLine(line);
        }

答案 1 :(得分:2)

以下是否会改变您的代码帮助?

我认为使用(.hasNext())测试最终写入会更容易 而不是关闭和打开新的文件流。

这是您的问题,当您的文件仍处于打开状态时,您尝试打开具有写访问权限的文件。

using (FileStream aFile = new FileStream(path, FileMode.Append, FileAccess.Write))
    {
        using (StreamWriter sw = new StreamWriter(aFile))
        {
            while ((line = reader.ReadLine()) != null)
            {                       
                var delimiter = string.Empty; 

                string[] tokens = line.Split(new char[] { ' ', '\t', '(', ')', ',' }, StringSplitOptions.RemoveEmptyEntries);

                if(tokens.hasNext())
                { delimiter = ","; }
                else 
                { delimiter = "."; }

                if (tokens[1].Equals(ColChangable1) || tokens[1].Equals(ColChangable2))
                {
                    sw.WriteLine(tokens[0] + "\t" + "\"TRIM(:" + tokens[0] + ")\" + delimiter);
                }

                else if (tokens[1].Equals(ColChangable3))
                {
                    sw.WriteLine(tokens[0] + "\t" + delimiter);
                }
                else if (tokens[1].Equals(ColChangable4))
                {
                    sw.WriteLine(tokens[0] + "\t" + "DATE" + delimiter);
                }                        
            }
        }                
    }
}

答案 2 :(得分:1)

如果我理解您的问题,更简单的方法是使用System.IO.File。 Demo on .NetFiddle

using System;
using System.IO;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        // init
        var path = "output.ctl";
        var content =
            "Hello and Welcome" + Environment.NewLine
            + "Hello and Welcome" + Environment.NewLine
            + ",";
        File.WriteAllText(path, content);

        var text = File.ReadAllLines(path); // read the file as string[]

        foreach (var line in text) // print the file
            Console.WriteLine(line);

        text[text.Length - 1] = text.Last().Replace(",", "."); // replace

        File.WriteAllLines(path, text); // overwrite or write to a new file

        string[] lines2 = File.ReadAllLines(path); // read again
        foreach (var line in lines2) // then print to show the difference
            Console.WriteLine(line);
    }
}

输出:

Hello and Welcome
Hello and Welcome
,
Hello and Welcome
Hello and Welcome
.

答案 3 :(得分:0)

对于较小的文件,您可以使用:

public void Replace(string inputFile, string outputFile)
    {
        File.WriteAllText(outputFile, Regex.Replace(File.ReadAllText(inputFile), @",\s*$", "."));
    }