读写文本文件

时间:2019-12-12 08:45:58

标签: c#

我想读取文本文件,更改格式,然后将其输出到其他文件中。

我得到以下代码来读取原始文本文件并将其读取到另一个文件中。如何更改格式?

原始文本文件

116

11/2/2012 18:22

N9 45.483 E10 30.495

416 m

117

11/2/2012 18:22

N9 45.483 E10 30.495

415 m

更改格式后的新文本文件

116,11/2/2012 18:22,N9 45.483 E10 30.495,416 m
117,11/2/2012 18:22,N9 45.483 E10 30.495,415 m

源代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Reading_textfile
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\Users\ryuma\Downloads\Elephantread.txt";

            //string[] Lines = File.ReadAllLines(filePath);

            List<string> lines = new List<string>();
            lines = File.ReadAllLines(filePath).ToList();

            foreach (String line in lines)
            {
                Console.WriteLine(line);
            }

            string filePath2 = @"C:\Users\ryuma\OneDrive\Desktop\WriteFile.txt";
            File.WriteAllLines(filePath2, lines);
            Console.ReadLine();
        }
    }
}

3 个答案:

答案 0 :(得分:0)

如果添加对System.Linq的引用,这应该可以工作

        var srcLines = File.ReadAllLines(filePath);

        var text = string.Join(",", File.ReadAllLines(filePath));
        var dstLines = text.Split(new []{" m,", " m"}, StringSplitOptions.RemoveEmptyEntries).Select(x => x + " m");
        string filePath2 = @"C:\Users\ryuma\OneDrive\Desktop\WriteFile.txt";
        File.WriteAllLines(filePath2, destLines);

答案 1 :(得分:0)

您可以将文件阅读为文本,这样操作起来会更容易:

var input = File.ReadAllText(filePath);
var output = input.Replace("\r","").Replace("\n\n",",").Replace("m","m\n");
File.WriteAllText(output);

这个想法是用,替换新行(以与系统无关的方式进行,否则使用this solution),然后在m字符后添加新行。

答案 2 :(得分:0)

我建议以一种可读且干净的方式进行操作。

static void ChangeFormatInDestination(string sourcePath, string destinationPath)
    {
        try
        {
            if (File.Exists(sourcePath))
            {
                string[] allLines = File.ReadAllLines(sourcePath);
                // Merge all non-null lines in one line separated by commas
                var convertedSingleLine = string.Join(",", 
                                allLines.Where(s=>!string.IsNullOrEmpty(s)));
                // Replace the " m,"
                convertedSingleLine = convertedSingleLine.Replace(" m,",
                                      " m" + System.Environment.NewLine);

                File.WriteAllText(destinationPath, convertedSingleLine);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"There was an error while manipulating the files. Exception: {ex.Message}");
        }
    }