Click here to Skip to main content
15,879,096 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
Updated 3-Oct-12 23:37pm
v2
Comments
Rockstar_ 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 4-Oct-12 3:12am    
I am reading it line by line.
Guirec 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 4-Oct-12 6:23am    
What is count variable? A field?

And what is wrong with using string.Replace()?

C#
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:
C#
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();
}
 
Share this answer
 
v4
Comments
DhanashreeRamya 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 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 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 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?
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);"
C#
string temp = orignal.Substring(0, orignal.IndexOf(oldv));
string temp2 = orignal.Substring(orignal.IndexOf(oldv) + oldv.Length);
return temp + newv + temp2;
 
Share this answer
 
Comments
DhanashreeRamya 4-Oct-12 4:59am    
this still doesn't replace the last line of the file.
Mohd. Mukhtar 4-Oct-12 5:02am    
Could you please post the code from where you calling ReplaceFirstOccurrance method?

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