如何删除特定记录(固定长度)包括.txt文件中的数据?

时间:2015-05-14 00:29:33

标签: c# file record

我是C#的新手,我正在制作项目,但我无法删除此部分..

如果我将.txt文件中的数据保存在一行中,但包含许多没有分隔符的固定长度记录,如果每条记录都有固定长度,并且每个字段都有固定长度并保存在文件中,就像这样

1ahly2zamalek

如何从输入到程序ID = 2的行中删除记录2zamalek

public team()
        {
            Team_ID_Len = 5;
            Team_Name_Len = 10;
            Team_Rec_Len = 15; ;

            Team_ID = new char[Team_ID_Len];
            Team_Name = new char[Team_Name_Len];
        }

3 个答案:

答案 0 :(得分:1)

听起来像是在寻找Substring。给它一个开始(记录长度*多少)和长度(记录长度)。

实际上,您可能希望将字符串创建为string s = part1+part2,其中part1是从0到记录开头的子字符串,part2是NEXT记录的开头,直到最后。

然后保存它。

答案 1 :(得分:0)

您的号码是您的分隔符,split with a char array

使用System;

using System;

public static class Program
{
    public static void Main()
    {
        string words = "1sdklfjlsdf2lksjdf3sfd4sfd5fsd6fsd7fsd8fsd9sfd10aslkdfj11jklh12hjk";
        int deleteRecordId = 11;
        string [] split = words.Split(new Char [] {'1', '2','3','4','5','6','7','8','9','0'});

        string newString = "";
        int j = 0;
        for( int i = 0; i < split.Length; i++)
        {

            if ( j == deleteRecordId)
            {
             //ignore this record
             Console.WriteLine("ignore i = " + i);
                j++;
            }
            else
            {
                Console.WriteLine("i = " + i);
                if(!( split[i] == ""))
                {
                    newString += j +  split[i];
                    j++;
                }
            }

        }
        Console.WriteLine(newString);
    }


}

然后将WriteAll写入文件

答案 2 :(得分:-1)

尝试此功能,它对我来说100%工作:

    public static void DeleteRecordFromFile(string filePath, string id)
    {
        string txt = System.IO.File.ReadAllText(filePath);
        Regex rx = new Regex("^[0-9]$");
        foreach (var chars in txt.ToCharArray())
        {
            if (rx.IsMatch(chars.ToString()))
            {
                txt = txt.Insert(txt.IndexOf(chars), "*");
            }
        }
        txt = txt.Trim('*');
        string newtxt = string.Empty;
        foreach (var block in txt.Split('*'))
        {
            if (block.Trim().Substring(0, 1) == id)
            {
                continue;
            }
            newtxt += block;
        }
        System.IO.File.WriteAllText(filePath, newtxt);
    }
相关问题