Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Function to Find and Replace in C#

Function to Find and Replace in C#

Scheduled Pinned Locked Moved C#
csharpxmlquestion
7 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G Offline
    G Offline
    GrgBalden
    wrote on last edited by
    #1

    Hi All, I've been putting together a short program too automatically to find and replace a string within all files of a directory. For my first set of replacements I want to replace: • “>” with “>” • “<” with “<” Program.CS

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;

    namespace XMLReformat
    {
    class Program
    {
    static void Main(string[] args)
    {

            //Console.WriteLine("Please Enter the directory of XML Documents:\\n");
            //string userDir = Console.ReadLine();
    
            string userDir = "C:\\\\xmlreformat";
    
            try
            {
                string\[\] filePaths = Directory.GetFiles(userDir);
                foreach (string i in filePaths)
                {
                    // Call reformat operation
    
                    Reformat.Replace(i);
    
                }
                Console.WriteLine("Operation Succeeded \\n \\n Press Any Key to Exit");
                Console.ReadKey();
            }
            catch (Exception e)
            {
                Console.WriteLine("Directory Not Found:" + e.Message);
                Console.WriteLine("\\n \\n Press Any Key to Exit");
                Console.ReadKey();
            }
    
            
    
        }
    }
    

    }

    Reformat.CS

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;

    namespace XMLReformat
    {
    class Reformat
    {

        public static void Replace(string FName)
        {
            StreamReader File = new StreamReader(FName); // create new streamreader
            
            string fileContent = File.ReadToEnd(); // create new string, read file into string
            File.Close();
    
    
            StreamWriter NewFile = new StreamWriter(FName); // create new stream writer
    
            string fileContentCopy = fileContent;
    
            string istring1 = "&gt;";
            string ostring1 = ">";
    
            string istring2 = "&lt;";
            string ostring2 = "<";
    
            fileContentCopy.Replace(istring1, ostring1);
            fileContentCopy.Replace(istring2, ostring2);
    
    
            fileContent = fileContentCopy;
    
            NewFile.Write(fileContent);
    
    
        }
    
    
    }
    

    }

    However when I run the program it doesnt seem to work at all. Any ideas? Thanks, George

    M P 2 Replies Last reply
    0
    • G GrgBalden

      Hi All, I've been putting together a short program too automatically to find and replace a string within all files of a directory. For my first set of replacements I want to replace: • “>” with “>” • “<” with “<” Program.CS

      using System;
      using System.Collections.Generic;
      using System.Text;
      using System.IO;

      namespace XMLReformat
      {
      class Program
      {
      static void Main(string[] args)
      {

              //Console.WriteLine("Please Enter the directory of XML Documents:\\n");
              //string userDir = Console.ReadLine();
      
              string userDir = "C:\\\\xmlreformat";
      
              try
              {
                  string\[\] filePaths = Directory.GetFiles(userDir);
                  foreach (string i in filePaths)
                  {
                      // Call reformat operation
      
                      Reformat.Replace(i);
      
                  }
                  Console.WriteLine("Operation Succeeded \\n \\n Press Any Key to Exit");
                  Console.ReadKey();
              }
              catch (Exception e)
              {
                  Console.WriteLine("Directory Not Found:" + e.Message);
                  Console.WriteLine("\\n \\n Press Any Key to Exit");
                  Console.ReadKey();
              }
      
              
      
          }
      }
      

      }

      Reformat.CS

      using System;
      using System.Collections.Generic;
      using System.Text;
      using System.IO;

      namespace XMLReformat
      {
      class Reformat
      {

          public static void Replace(string FName)
          {
              StreamReader File = new StreamReader(FName); // create new streamreader
              
              string fileContent = File.ReadToEnd(); // create new string, read file into string
              File.Close();
      
      
              StreamWriter NewFile = new StreamWriter(FName); // create new stream writer
      
              string fileContentCopy = fileContent;
      
              string istring1 = "&gt;";
              string ostring1 = ">";
      
              string istring2 = "&lt;";
              string ostring2 = "<";
      
              fileContentCopy.Replace(istring1, ostring1);
              fileContentCopy.Replace(istring2, ostring2);
      
      
              fileContent = fileContentCopy;
      
              NewFile.Write(fileContent);
      
      
          }
      
      
      }
      

      }

      However when I run the program it doesnt seem to work at all. Any ideas? Thanks, George

      M Offline
      M Offline
      musefan
      wrote on last edited by
      #2

      GrgBalden wrote:

      fileContentCopy.Replace(istring1, ostring1); fileContentCopy.Replace(istring2, ostring2);

      String.Replace function returns an altered string, it does not change the instance itself. You need to use...

      fileContentCopy = fileContentCopy.Replace(istring1, ostring1);
      fileContentCopy = fileContentCopy.Replace(istring2, ostring2);

      I would also like to add that reading a whole file to a string, in my opinion, is not a good thing. I would prefer to read a character at a time and match it to a set of keywords and replace any matches.

      Life goes very fast. Tomorrow, today is already yesterday.

      G 1 Reply Last reply
      0
      • M musefan

        GrgBalden wrote:

        fileContentCopy.Replace(istring1, ostring1); fileContentCopy.Replace(istring2, ostring2);

        String.Replace function returns an altered string, it does not change the instance itself. You need to use...

        fileContentCopy = fileContentCopy.Replace(istring1, ostring1);
        fileContentCopy = fileContentCopy.Replace(istring2, ostring2);

        I would also like to add that reading a whole file to a string, in my opinion, is not a good thing. I would prefer to read a character at a time and match it to a set of keywords and replace any matches.

        Life goes very fast. Tomorrow, today is already yesterday.

        G Offline
        G Offline
        GrgBalden
        wrote on last edited by
        #3

        Hi, Thanks for the help I've added your suggestion and it seems to be working; I'm now trying to change the file extention of the files in the directory from .txt to .xml The text files already have the xml, i just need to change the file extention? Any ideas? I tried to impliment an Ext Changer class (last in the list) but doesnt seem to work? Any provide any sample code? Program.CS

        using System;
        using System.Collections.Generic;
        using System.Text;
        using System.IO;

        namespace XMLReformat
        {
        class Program
        {
        static void Main(string[] args)
        {

                //Console.WriteLine("Please Enter the directory of XML Documents:\\n");
                //string userDir = Console.ReadLine();
        
                string userDir = "C:\\\\xmlreformat";
        
                try
                {
                    string\[\] filePaths = Directory.GetFiles(userDir);
                    foreach (string i in filePaths)
                    {
                        // Call reformat operation
        
                        Reformat.Replace(i);
                        //ExtChanger.WriteFileName(i, userDir);
                       
        
                    }
                    Console.WriteLine("Operation Succeeded \\n \\n Press Any Key to Exit");
                    Console.ReadKey();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Directory Not Found:" + e.Message);
                    Console.WriteLine("\\n \\n Press Any Key to Exit");
                    Console.ReadKey();
                }
        
                
        
            }
        }
        

        }

        Reformat.cs

        using System;
        using System.Collections.Generic;
        using System.Text;
        using System.IO;

        namespace XMLReformat
        {
        class Reformat
        {

            public static void Replace(string FName)
            {
                StreamReader File = new StreamReader(FName); // create new streamreader
                
                string fileContent = File.ReadToEnd(); // create new string, read file into string
                File.Close();
        
        
                StreamWriter NewFile = new StreamWriter(FName); // create new stream writer
        
                string fileContentCopy = fileContent;
        
                string istring1 = "&gt;";
                string ostring1 = ">";
        
                string istring2 = "&lt;";
                string ostring2 = "<";
        
                fileContentCopy = fileContentCopy.Replace(istring1, ostring1);
                fileContentCopy = fileContentCopy.Replace(istring2, ostring2);
        
        
                fileContent = fileContentCopy;
        
                N
        
        M 1 Reply Last reply
        0
        • G GrgBalden

          Hi All, I've been putting together a short program too automatically to find and replace a string within all files of a directory. For my first set of replacements I want to replace: • “>” with “>” • “<” with “<” Program.CS

          using System;
          using System.Collections.Generic;
          using System.Text;
          using System.IO;

          namespace XMLReformat
          {
          class Program
          {
          static void Main(string[] args)
          {

                  //Console.WriteLine("Please Enter the directory of XML Documents:\\n");
                  //string userDir = Console.ReadLine();
          
                  string userDir = "C:\\\\xmlreformat";
          
                  try
                  {
                      string\[\] filePaths = Directory.GetFiles(userDir);
                      foreach (string i in filePaths)
                      {
                          // Call reformat operation
          
                          Reformat.Replace(i);
          
                      }
                      Console.WriteLine("Operation Succeeded \\n \\n Press Any Key to Exit");
                      Console.ReadKey();
                  }
                  catch (Exception e)
                  {
                      Console.WriteLine("Directory Not Found:" + e.Message);
                      Console.WriteLine("\\n \\n Press Any Key to Exit");
                      Console.ReadKey();
                  }
          
                  
          
              }
          }
          

          }

          Reformat.CS

          using System;
          using System.Collections.Generic;
          using System.Text;
          using System.IO;

          namespace XMLReformat
          {
          class Reformat
          {

              public static void Replace(string FName)
              {
                  StreamReader File = new StreamReader(FName); // create new streamreader
                  
                  string fileContent = File.ReadToEnd(); // create new string, read file into string
                  File.Close();
          
          
                  StreamWriter NewFile = new StreamWriter(FName); // create new stream writer
          
                  string fileContentCopy = fileContent;
          
                  string istring1 = "&gt;";
                  string ostring1 = ">";
          
                  string istring2 = "&lt;";
                  string ostring2 = "<";
          
                  fileContentCopy.Replace(istring1, ostring1);
                  fileContentCopy.Replace(istring2, ostring2);
          
          
                  fileContent = fileContentCopy;
          
                  NewFile.Write(fileContent);
          
          
              }
          
          
          }
          

          }

          However when I run the program it doesnt seem to work at all. Any ideas? Thanks, George

          P Offline
          P Offline
          PIEBALDconsult
          wrote on last edited by
          #4

          System.Web.HttpUtility.HtmlEncode and System.Web.HttpUtility.HtmlDecode

          G 1 Reply Last reply
          0
          • P PIEBALDconsult

            System.Web.HttpUtility.HtmlEncode and System.Web.HttpUtility.HtmlDecode

            G Offline
            G Offline
            GrgBalden
            wrote on last edited by
            #5

            Thanks for the pointer, I was hoping that someone would know how to change a file extention by changing the file extention using a string? Any more ideas?

            P 1 Reply Last reply
            0
            • G GrgBalden

              Hi, Thanks for the help I've added your suggestion and it seems to be working; I'm now trying to change the file extention of the files in the directory from .txt to .xml The text files already have the xml, i just need to change the file extention? Any ideas? I tried to impliment an Ext Changer class (last in the list) but doesnt seem to work? Any provide any sample code? Program.CS

              using System;
              using System.Collections.Generic;
              using System.Text;
              using System.IO;

              namespace XMLReformat
              {
              class Program
              {
              static void Main(string[] args)
              {

                      //Console.WriteLine("Please Enter the directory of XML Documents:\\n");
                      //string userDir = Console.ReadLine();
              
                      string userDir = "C:\\\\xmlreformat";
              
                      try
                      {
                          string\[\] filePaths = Directory.GetFiles(userDir);
                          foreach (string i in filePaths)
                          {
                              // Call reformat operation
              
                              Reformat.Replace(i);
                              //ExtChanger.WriteFileName(i, userDir);
                             
              
                          }
                          Console.WriteLine("Operation Succeeded \\n \\n Press Any Key to Exit");
                          Console.ReadKey();
                      }
                      catch (Exception e)
                      {
                          Console.WriteLine("Directory Not Found:" + e.Message);
                          Console.WriteLine("\\n \\n Press Any Key to Exit");
                          Console.ReadKey();
                      }
              
                      
              
                  }
              }
              

              }

              Reformat.cs

              using System;
              using System.Collections.Generic;
              using System.Text;
              using System.IO;

              namespace XMLReformat
              {
              class Reformat
              {

                  public static void Replace(string FName)
                  {
                      StreamReader File = new StreamReader(FName); // create new streamreader
                      
                      string fileContent = File.ReadToEnd(); // create new string, read file into string
                      File.Close();
              
              
                      StreamWriter NewFile = new StreamWriter(FName); // create new stream writer
              
                      string fileContentCopy = fileContent;
              
                      string istring1 = "&gt;";
                      string ostring1 = ">";
              
                      string istring2 = "&lt;";
                      string ostring2 = "<";
              
                      fileContentCopy = fileContentCopy.Replace(istring1, ostring1);
                      fileContentCopy = fileContentCopy.Replace(istring2, ostring2);
              
              
                      fileContent = fileContentCopy;
              
                      N
              
              M Offline
              M Offline
              musefan
              wrote on last edited by
              #6

              Try using the FileInfo class (in System.IO)...

              FileInfo fi = new FileInfo("");//use actual filepath
              string NewFN = fi.Name.SubString(0, fi.Name.Length - fi.Extension.Length);//Get file name without extension
              NewFN += ".XML";

              //then use MoveTo to effectively rename the file
              fi.MoveTo(fi.DirectoryName + NewFN, true);
              //true is used to specify the target file will be overwrote if it already exists.

              That should do the trick for you ;)

              Life goes very fast. Tomorrow, today is already yesterday.

              1 Reply Last reply
              0
              • G GrgBalden

                Thanks for the pointer, I was hoping that someone would know how to change a file extention by changing the file extention using a string? Any more ideas?

                P Offline
                P Offline
                PIEBALDconsult
                wrote on last edited by
                #7

                System.IO.Path.GetFileNameWithoutExtension and System.IO.File.Move

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups