gpt4 book ai didi

c#索引文本文件的简单方法

转载 作者:太空宇宙 更新时间:2023-11-03 16:06:10 25 4
gpt4 key购买 nike

我是 C# 编程的新手,我有一个问题:我想在行首添加索引号,示例:

1. m.vardas  m.pavarde  m.adresas  m.telnum  m.uzrasai

我认为一定有比读取文件并计算所有行数以获得文件中的行数更好的方法。这是我的代码:

    class Mokiniai // students
{
struct Mokinys // student
{
public string vardas; // name
public string pavarde; //last name
public string adresas; //address
public string telnum; //phone number
public string uzrasai; //notes
};
//.........................................................
public static void mokirasymas()
{
Mokinys m;
//...................................................
Console.WriteLine("Iveskite Mokinio varda: "); // input student name
m.vardas = Console.ReadLine();
Console.WriteLine("Iveskite Mokinio pavarde: "); // input student lastname
m.pavarde = Console.ReadLine();
Console.WriteLine("Iveskite Mokinio adresa: "); // input address
m.adresas = Console.ReadLine();
Console.WriteLine("Iveskite Mokinio telefono numeri: "); //input number
m.telnum = Console.ReadLine();
Console.WriteLine("Iveskite pastabas apie Mokini: "); //input notes
m.uzrasai = Console.ReadLine();
string mokinys = String.Format("|{0,15}|{1,15}|{2,15}|{3,15}|{4,15}|", m.vardas, m.pavarde, m.adresas, m.telnum, m.uzrasai);
using (TextWriter writer = File.AppendText("text.txt"))
{
//
// Only first time when program is used
//
//writer.WriteLine("|-------------------------------------------------------------------------------|");
//writer.WriteLine("| Vardas | Pavarde | Adresas | Tel.Numeris | Pastabos |");
//writer.WriteLine("|-------------------------------------------------------------------------------|");
//
//
//
writer.Write(mokinys);
//
// Iraso nauja eilute i faila
//
writer.Write(writer.NewLine);
}
}

感谢您的帮助。

最佳答案

可能有比读取整个文件来计算行数更好的方法(读取最后一行?你能相信吗?)文件中有多少行没有特殊的文件属性。

如果你想知道你使用的行数File.ReadLines() .

注意关于 ReadLines 与 ReadAllLines 的区别:

The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.

这是一个例子:

var numLines = File.ReadLines(@"text.txt").Count();

然后您只需将其添加到您的格式字符串即可。

关于c#索引文本文件的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19272562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com