Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey Everyone :)

I have a little problem. Let me explain the workplace.

My Text File Structure:
X_OFFSET 0
Y_OFFSET 0
IDSTART
0001 222 222 222 222
0002 250 500 250
0003 1700 500 500 250
0004 900 600 500 250
0005 1350 250 500 250
IDEND

What I must do is to find the IDSTART-IDEND block and DELETE a spesific line between them.

Example: User set id1 123 124 125 126 => id1 means ID, 123 means Center X, 124 means Center Y, 125 means Center Z and 126 means Radius.

Workplace:
The user will enter the id number(such as id5) to a text box, then click a button to delete the whole line starting with "id5"...

is this possible? if it is, How can I make it?

[Improved_v2]


Okey, I've made some changes and it works now. But, there is problem.
        FileStream fs = new FileStream("C:\hucre.txt", FileMode.Open);
        StreamReader okuma = new StreamReader(fs);
        string Metin = okuma.ReadToEnd();

        char[] Ayrac = { '\n' };
        MetinSplit = Metin.Split(Ayrac);

        for (int i = 0; i < MetinSplit.Length; i++)
        {
            GeciciDizi.Add("a");
            GeciciDizi2.Add("b");
        }
        // MetinSplit'i GeciciDiziye At.
        for (int i = 0; i < MetinSplit.Length; i++)
        {
            GeciciDizi[i] = MetinSplit[i];
        }

        for (int i = 0; i < MetinSplit.Length; i++)
        {
            GeciciDizi2[i] = MetinSplit[i];
        }

        for (int i = 0; i < GeciciDizi.Count; i++)
        {
            if((string)GeciciDizi[i]==SilinecekDeger)
                GeciciDizi.RemoveAt(i);
        }
        for (int i = 0; i < GeciciDizi.Count; i++)
        {
            GeciciDizi2[i] = GeciciDizi[i];
        }

        okuma.Close();
        fs.Close();
        FileStream newFile = new FileStream("C:\\hucretemp.txt",      FileMode.Open);

        StreamWriter yaz = new StreamWriter(newFile);
        for (int i = 0; i < GeciciDizi2.Count; i++)
        {
            yaz.WriteLine(GeciciDizi2[i]);
        }

        yaz.Close();
        yeniFile.Close();
        File.Delete("C:\\hucre.txt");

        File.Move(@"C:\\hucretemp.txt",   @"C:\\hucre.txt");
    }
}


Here, the problem is this.

When I read from the file hucre.txt to my tempArrayList, it wrtes to array like this below.

X_OFFSET 0\r\n
Y_OFFSET 0\r\n
IDSTART\r\n
0001 222 222 222 222\r\n
0002 250 500 250\r\n
0003 1700 500 500 250\r\n
0004 900 600 500 250\r\n
0005 1350 250 500 250\r\n
IDEND

it adds one more \r.

So, when I want to read something from the "hucre.txt",
I can't managed to do it, because
it becomes like this 0001 222 222 222 222\r\r\n

How can I remove it?

I really am desperate, please help :/

My best regards...
Posted
Updated 7-Jun-11 6:39am
v8
Comments
BobJanova 31-May-11 8:45am    
This is very similar to your question here:
http://www.codeproject.com/Questions/202599/Write-to-File-Problem-Overriding.aspx
Perhaps you should merge them.

Also, this feels very much like homework. If it is not, why are you using this specific file format? It is not really a good one.
Un_NaMeD 31-May-11 8:48am    
it is actually. I wish I could use a database :/
Rob Branaghan 31-May-11 8:50am    
Cant you rewrite using XML? it would be far easier! OR save a Prefix and Suffix to each line

If this file is not going to be too big, you could load this file into an array (line by line of course), delete the specific lines and then write the remaining lines back to the file.

This thread[^] could give you some other approaches as well.
 
Share this answer
 
Comments
Un_NaMeD 31-May-11 9:21am    
This seems a nice suggestion. I'll give it a try.
Abhinav S 1-Jun-11 0:10am    
Thanks. Give it a try.
Un_NaMeD 4-Jun-11 15:34pm    
Hi sir.
I tried to do what you say, but I couldn't make it.
I posted the code, if you have time, could you please have look at it?
Thank you...
Sergey Alexandrovich Kryukov 31-May-11 16:18pm    
Not perfect due to the issue you mentioned yourself (file size) and also some performance hit. Anyway, my 5.
Please see my answer.
--SA
Abhinav S 1-Jun-11 0:10am    
Yes not the best solution in terms of large file size - thanks for the 5 though.
What Abhinav suggested is not so practical in terms of performance and may not be suitable for big files.

Here is what you can do:

C#
static void CopyFileWithExcludedLine(string inputFileName, string outputFileName, ulong excludeLine) {
    ulong lineCounter = 0;
    System.IO.StreamWriter writer = null;
    using (System.IO.StreamReader reader = new System.IO.StreamReader(inputFileName, true)) {
        try {
            while (reader.Peek() >= 0) {
                string line = reader.ReadLine();
                if (writer == null)
                    writer =
                       new System.IO.StreamWriter(
                           outputFileName, false,
                           reader.CurrentEncoding);
                if (lineCounter != excludeLine)
                    writer.WriteLine(line);
                lineCounter++;
            } //loop
        } finally {
            if (writer != null)
                writer.Dispose();
        } //exception
    } //using
} //CopyFileWithExcludedLine


Most complex thing here is my solution for encoding. I reproduce encoding of the input file in the output file, but input encoding is accessible only after first read operation. That's why I applied lazy initialization of the writer (when encoding is already known) and added an extra try-finally block (using cannot be used, but the try-catch block is perfectly identical in function.

If you know encoding, the code will be much more simple.

—SA
 
Share this answer
 
v2
Comments
Abhinav S 1-Jun-11 0:10am    
This should work. 5.
Sergey Alexandrovich Kryukov 1-Jun-11 0:25am    
Certainly.
Thank you, Abhinav.
--SA
Wonde Tadesse 4-Jun-11 18:50pm    
Good answer. 5+
Sergey Alexandrovich Kryukov 4-Jun-11 20:40pm    
Thank you, Wonder.
--SA
Espen Harlinn 5-Jun-11 5:49am    
Good effort, my 5
[Answering a follow-up question about encoding]

Text files comes with different encodings. When you read file in one encoding assuming a different encoding, you may or may not screw up the content of the file. It also depends on the actual set of code points used in the file — for example if all code points lie in the ASCII range, UTF-8 encoding and ANSI encoding will give identical results if UTF-8 without BOM is ised. Encoding issues are covered by the class System.Text.Encoding and derived classes, see http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx[^].

Encodings are roughly subdivided into Unicode UTFs and the encodings used prior to Unicode. .NET supports Unicode. Unicode at its core does not define encodings. It defines one-to-one correspondence between characters as cultural entities, regardless fonts, glyphs, etc., and a set of abstract mathematical numbers (code points), totally abstracted from their computer presentation such as size, little- of big-endian, etc. Instead, a set of different UTF encodings is defined. Unicode is not a 16-bit encoding! It standardize much more code points than 216! Even UTF-8 and UTF-16 UTFs support them all (in this way, a character is not one byte or two bytes — it takes 1 to 4 bytes, in fact). They have different convenience in different situations. A text file may or may not contain Byte-Order Marker (BOM) at the beginning of the file, which helps to recognize UTF encoding before reading.

For more information, use:
http://unicode.org/[^],
http://unicode.org/faq/utf_bom.html[^].

—SA
 
Share this answer
 
v2
Comments
Espen Harlinn 7-Jun-11 18:37pm    
Good stuff, my 5
Sergey Alexandrovich Kryukov 7-Jun-11 21:49pm    
Thank you, Espen.
--SA
Un_NaMeD 8-Jun-11 7:44am    
nice definition, efficient links.
It helped me to understand your coding. Thank you, my 5...
Sergey Alexandrovich Kryukov 8-Jun-11 13:02pm    
Sure. You are welcome.
Will you formally accept the answer (green button)? You can accept more than one.
Thank you.
--SA
Hope this does something close to what you need to read the lines into a List, so you can sort though them.

C#
public List<string> FileToList(string filePath)
{
    string content = null;
    List<string> lines = new List<string>(){};
    System.IO.StreamReader sr = null;
    // read the file's lines into a List
    try {
        sr = new System.IO.StreamReader(filePath);
        while (sr.Peek() >= 0) {
            lines.Add(sr.ReadLine());
        }
    } finally {
        if ((sr != null))
            sr.Close();
    }
  
    return lines;
}</string></string></string>


Then when you save them back just overwrite the file with the remaining list.

Maybe that will work?
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 31-May-11 16:20pm    
You don't need list of lines. Also, you don't take encoding into account. So, my 4.
Please see my solution.
--SA
Here is a quick console test that achieves your basic goal, tweak it as you need to fit your needs, but it gives a simple way to remove lines that start with a given ID, if none of the other lines in the file start with "ID like" text, no worries.

List<string> lines = File.ReadAllLines(@"J:\test.txt").ToList();

int removeCount = lines.RemoveAll(item => item.StartsWith("0005"));

Console.WriteLine(String.Format("Removed {0} line(s).", removeCount));


Good luck!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900