Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
The following is the code for replacing fist occurrence of a string in a file.
public static string ReplaceFirstOccurrance(string original, string oldValue, string newValue)
{
    if (String.IsNullOrEmpty(original))
        return String.Empty;
    if (String.IsNullOrEmpty(oldValue))
        return original;
    if (String.IsNullOrEmpty(newValue))
        newValue = String.Empty;
    int loc = original.IndexOf(oldValue);
    if(loc==-1)
       return original;
    return original.Remove(loc, oldValue.Length).Insert(loc, newValue);
}
 
 
If the string that I want to replace is the last line of the file then it is not getting replaced.Any idea why this is happening?
 
This is the code from where I am calling the function
 
 private void Transform_Click(object sender, EventArgs e)
        {
                      FileStream fread = new FileStream(despath, FileMode.Open);
                            StreamReader sfread = new StreamReader(fread);
                            string txt = sfread.ReadToEnd();
                            fread.Close();
                            
                            string actual ="This is actual Sample";
                       
                            string replace = "This is replaced line"+count;
                       
                            string replaceVariable = ReplaceFirstOccurrance(txt, actual, replace);
                         
                            FileStream filewrite = new FileStream(despath, FileMode.Create);
                            StreamWriter filew = new StreamWriter(filewrite);
 
                            filew.Write(replaceVariable);
 
                            filew.Close();
                            filewrite.Close();
                            count++;
}
 
If "This is actual sample" is the last line in the file,it is not getting replaced.
Posted 3-Oct-12 21:04pm
Edited 3-Oct-12 23:37pm
v2
Comments
VijayChauhan123 at 4-Oct-12 3:10am
   
Are you reading the file line by line or using function readtoend(). make sure that it is reading the last line or not..
DhanashreeRamya at 4-Oct-12 3:12am
   
I am reading it line by line.
Guirec Le Bars at 4-Oct-12 3:35am
   
Whether your function is not called at all for the last line, whether your "oldValue" is not in the line... Your function should work fine. Problem must be external.
n.podbielski at 4-Oct-12 6:23am
   
What is count variable? A field?
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

because it deletes the position, insert() doesnt find any loc
try this instead for your line return "original.Remove(loc, oldValue.Length).Insert(loc, newValue);"
string temp = orignal.Substring(0, orignal.IndexOf(oldv));
string temp2 = orignal.Substring(orignal.IndexOf(oldv) + oldv.Length);
return temp + newv + temp2;
  Permalink  
Comments
DhanashreeRamya at 4-Oct-12 4:59am
   
this still doesn't replace the last line of the file.
Mohd. Mukhtar at 4-Oct-12 5:02am
   
Could you please post the code from where you calling ReplaceFirstOccurrance method?
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

And what is wrong with using string.Replace()?
 
if (original==null) return string.Empty
else return original.Replace(oldValue, newValue);
 
Also, you are not reading file line by line, you read it whole at once into one string. If you have "This is actual sample" in 2 or more places, only first will be replaced.
 
Reading and replaceing line by line:
private void Transform_Click(object sender, EventArgs e)
{
    FileStream fread = new FileStream(despath, FileMode.Open);
    StreamReader sfread = new StreamReader(fread);
    FileStream filewrite = new FileStream(despath, FileMode.Create);
    StreamWriter filew = new StreamWriter(filewrite);
 
    while (!sfread.EndOfStream)
    {
        string line = sfread.ReadLine();
        
        string replaceVariable = ReplaceFirstOccurrance(line, 
            "This is actual Sample", 
            "This is replaced line"+count.ToString());
                    
        filew.Write(replaceVariable);
count++;
    }    
    filew.Close();
    filewrite.Close();
    
fread.Close();
}
  Permalink  
v4
Comments
DhanashreeRamya at 4-Oct-12 6:24am
   
string.Replace will replace all the occurrences of the text,where as I want to replace only first occurrence.
sjelen at 4-Oct-12 6:55am
   
Ok, you're right. But your original code was replacing first occurrence in whole text, not in each line, and the problem was not in ReplaceFirstOccurrance but in Transform_Click.
I've updated the solution to use your ReplaceFirstOccurrance()
DhanashreeRamya at 4-Oct-12 7:45am
   
In what mode should I open my file because it is giving exception on 5th line that the file is used by other process.
sjelen at 5-Oct-12 13:03pm
   
If I counted ok, that's output file, it has to be opened in write mode.
What is the other process that uses it?
Did you opened it in some editor?

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 375
1 _Amy 235
2 Andreas Gieriet 180
3 Peter Leow 175
4 Dave Kreskowiak 155
0 OriginalGriff 7,540
1 Sergey Alexandrovich Kryukov 6,462
2 Maciej Los 3,849
3 Peter Leow 3,653
4 CHill60 2,712


Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 4 Oct 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100