简体   繁体   中英

C# Edit string in file - delete a character (000)

I am rookie in C#, but I need solve one Problem. I have several text files in Folder and each text files has this structure:

IdNr 000000100

Name Name

Lastname Lastname

Sex M

.... etc...

Load all files from Folder, this is no Problem ,but i need delete "zero" in IdNr, so delete 000000 and 100 leave there. After this file save. Each files had other IdNr , Therefore, it is harder :(

Yes, it is possible each files manual edit, but when i have 3000 files, this is not good :) Can C# one algorithm, which could this 000000 delete and leave only number 100?

Thank you All. Vaclav

So, thank you ALL ! But in the End I have this Code :-) :

using System.IO;

namespace name { public partial class Form1 : Form { public Form1() { InitializeComponent(); }

    private void Browse_Click(object sender, EventArgs e)
    {
        DialogResult dialog = folderBrowserDialog1.ShowDialog();
        if (dialog == DialogResult.OK)
            TP_zdroj.Text = folderBrowserDialog1.SelectedPath;

    }

    private void start_Click(object sender, EventArgs e)
    {

       try
       {
           foreach (string file in Directory.GetFiles(TP_zdroj.Text, "*.txt"))
           {
               string text = File.ReadAllText(file, Encoding.Default);

               text = System.Text.RegularExpressions.Regex.Replace(text, "IdNr    000*", "IdNr    ");
               File.WriteAllText(file, text, Encoding.Default);

           }
       }
           catch
       {
           MessageBox.Show("Warning...!");
               return;

           }

        {
            MessageBox.Show("Done");

        }

    }
}

}

Thank you ALL ! ;)

You can use int.Parse :

int number = int.Parse("000000100");
String withoutzeros = number.ToString();

According to your read/save file issue, do the files contain more than one record, is that the header or does each record is a list of key and value like "IdNr 000000100"? It's difficult to answer without these informations.

Edit : Here's a simple but efficient approach which should work if the format is strict:

var files = Directory.EnumerateFiles(path, "*.txt", SearchOption.TopDirectoryOnly);

foreach (var fPath in files)
{ 
    String[] oldLines = File.ReadAllLines(fPath); // load into memory is faster when the files are not really huge
    String key = "IdNr ";
    if (oldLines.Length != 0)
    {
        IList<String> newLines = new List<String>();
        foreach (String line in oldLines)
        {
            String newLine = line;
            if (line.Contains(key))
            {
                int numberRangeStart = line.IndexOf(key) + key.Length;
                int numberRangeEnd = line.IndexOf(" ", numberRangeStart);
                String numberStr = line.Substring(numberRangeStart, numberRangeEnd - numberRangeStart);
                int number = int.Parse(numberStr);
                String withoutZeros = number.ToString();
                newLine = line.Replace(key + numberStr, key + withoutZeros);
                newLines.Add(line);
            }
            newLines.Add(newLine);
        }
        File.WriteAllLines(fPath, newLines);
    }
}

These are the steps you would want to take:

  • Loop each file
  • Read file line by line
  • for each line split on " " and remove leading zeros from 2nd element
  • write the new line back to a temp file
  • after all lines processed, delete original file and rename temp file
  • do next file

(you can avoid the temp file part by reading each file in full into memory, but depending on your file sizes this may not be practical)


You can remove the leading zeros with something like this:

string s = "000000100";
s = s.TrimStart('0');

使用TrimStart

var trimmedText = number.TrimStart('0');

This should do it. It assumes your files have a .txt extension, and it removes all occurrences of "000000" from each file.

foreach (string fileName in Directory.GetFiles("*.txt"))
{
    File.WriteAllText(fileName, File.ReadAllText(fileName).Replace("000000", ""));
}

Simply, read every token from the file and use this method:

var token = "000000100";
var result = token.TrimStart('0');

You can write a function similar to this one:

static IEnumerable<string> ModifiedLines(string file) {
    string line;
    using(var reader = File.OpenText(file)) {
        while((line = reader.ReadLine()) != null) {
            string[] tokens = line.Split(new char[] { ' ' });
            line = string.Empty;
            foreach (var token in tokens)
            {
                line += token.TrimStart('0') + " ";
            }
            yield return line;
        }
    }
}

Usage:

File.WriteAllLines(file, ModifiedLines(file));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM