【问题标题】:How to display part of a line in a .txt file - C#如何在 .txt 文件中显示部分行 - C#
【发布时间】:2011-02-24 23:34:05
【问题描述】:

我需要一些基本的帮助。
我有一个文件夹,其中有一个文件。
File中有两行,行中的数据用“//”隔开。

例子:

在@"C:\ExampleFolder_ABCD\"位置有一个文件夹
在文件夹中有一个文件@"C:\ExampleFolder_ABCD\ExampleFile_ABCD.txt"
在文件中有两行:

名称_1 // 描述_1
名称_2 // 描述_2

我需要我的程序显示每行的第一部分、“//”之前的部分,并且只显示这部分。
我已经进行了一些研究,但希望得到一些实时帮助。

当然,任何帮助,无论好坏,都将不胜感激。
注意:这与作业无关。它涉及我的一个项目,它将帮助我整理我的电话簿。

洛夫罗·米尔尼克

如果您想测试,请将以下代码复制到新创建的命名空间中,编辑并执行它。

string MainDirectoryPath = @"C:\ExampleFolder_ABCD\"; // Example directory path - Completely random name (100% no overwrite)
string MainFileName = @"C:\ExampleFolder_ABCD\ExampleFile_ABCD.txt"; // Example file path - Completely random name (100% no overwrite)
Directory.CreateDirectory(MainDirectoryPath); // Create the directory.
StreamWriter CreateExampleFile = new StreamWriter(MainFileName); // Create the file.
CreateExampleFile.Close(); // Close the process.
StreamWriter WriteToExampleFile = File.AppendText(MainFileName); // Append text to the file.
WriteToExampleFile.WriteLine("Name_1 // Description_1"); // This line to append.
WriteToExampleFile.WriteLine("Name_2 // Description_2"); // This line to append.
WriteToExampleFile.Close(); // Close the process.
//
//
// I would like to know how to display both names in a list
// without the Description part of the line.
// Maybe with a command that contains "* // *" ??

【问题讨论】:

标签: c# list arraylist streamreader


【解决方案1】:

这里有一些代码:

StreamReader Reader = new StreamReader(MainFileName);
            char c = Convert.ToChar(@"/");
            Char[] splitChar = { c, c };
            String Line;
            while (!Reader.EndOfStream)
            {
                Line = Reader.ReadLine();
                String[] Parts;
                Parts = Line.Split(splitChar);
                foreach (string s in Parts)
                {
                    Console.WriteLine(s);
                }
            }
            Reader.Close();
            Console.WriteLine("Done");

【讨论】:

    【解决方案2】:

    我想你会在这里找到你需要的一切:http://www.dotnetperls.com/string-split

    中间有一堆来自文本文件的代码分割字符串,你可以在用类似的东西替换分割部分后使用它

    Regex.Split(myline, "\\\\")[0]
    

    它应该像一个魅力。

    【讨论】:

      【解决方案3】:

      从您发布的示例中,您需要做的就是拆分"\\\\" 上的每一行(您必须避开斜杠)。获取拆分的第一个结果,然后就可以了。

      【讨论】:

        【解决方案4】:

        另一种变体,在字符串对象上使用 Split 方法:

        var result = myString.Split(new char[] {'/','/'})[0]
        

        只需将找到“//”的字符串拆分为一个数组。然后你拉回数组中的第一个元素。

        【讨论】:

          猜你喜欢
          • 2016-05-11
          • 2021-04-01
          • 1970-01-01
          • 2020-10-08
          • 2021-01-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多