Community discussion forum

Basic request for code example

Tags:
  • 3 months ago

    Frank,

    You can use the code below. Let me know if you have any questions

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

    namespace DirectoryBrowser
    {
        class EntryPoint
        {
            static void Main(string[] args)
            {
                string directory        = @"C:\test";
                string searchPattern    = "*.txt"; //searches for files ending with .txt
                                                 //Can be replaces with * to search all files
                string searchValue      = "0X0D";
                StreamReader reader     = null;
                StreamWriter writer     = null;

                if (Directory.Exists(directory))
                {
                    /* Get all the files in the directory
                     * Note: If the are sub directories, you may want to get the sub diectories and iterate through them
                     */
                    FileInfo[] files = new DirectoryInfo(directory).GetFiles(searchPattern); //replace with new DirectoryInfo(directory).GetFiles() if searchPattern is not needed

                    //Read each file in the directory and check the contents.
                    foreach (FileInfo file in files)
                    {
                        reader = file.OpenText();
                        string content = reader.ReadToEnd();
                        reader.Close();
                        if (!content.EndsWith(searchValue))
                        {
                            writer = file.AppendText();
                            writer.WriteLine(searchValue);
                            writer.Flush();
                            writer.Close();
                        }
                    }
                }

                if (reader != null)
                    reader.Dispose();

                if (writer != null)
                    writer.Dispose();
            }
        }
    }

Post a reply

Enter your message below

Sign in or Join us (it's free).