I want to ask how to combine two text file and read in the rich text box..?

String rd = "";
        private void CLICK2_Click(object sender, EventArgs e)
        {
            string file1 = @"C:\Users\Fish\Desktop\fyp-coding\sample1.txt";
            string file2 = @"C:\Users\Fish\Desktop\fyp-coding\sample2.txt";

            FileStream fs1 = null;
            FileStream fs2 = null;

            try
            {
                fs1 = File.Open(file1, FileMode.Append);
                fs2 = File.Open(file2, FileMode.Open);

                byte[] fs2Content = new byte[fs2.Length];
                fs2.Read(fs2Content, 0, (int)fs2.Length);
                fs1.Write(fs2Content, 0, (int)fs2.Length);

                if (File.Exists(file1))
                {
                    StreamReader rfile = null;
                    try
                    {
                        rfile = new StreamReader(file1);
                        while ((rd = rfile.ReadLine()) != null)
                        {
                            s4.AppendLine(rd);
                        }
                        showFile2.AppendText(s4.ToString().Trim());

                    }
                    finally
                    {
                        rfile.Close();
                    }
                }

This is my coding..I need to show the new content after combine two files in the rich text box.Hope someone can help me..thanks

Dani AI

Generated

A few focused notes that address the NullReferenceException and a safer way to combine the files and show the result.

The exception you saw means some variable used on the line reported by the stack trace is null. In the code posted the usual suspects are: the StringBuilder s4 was never constructed, the StreamReader reference could be null when you call Close, or the RichTextBox control reference (your showFile2) is not the instance you expect (name mismatch or not created yet). Start by running with a breakpoint or look at the exception's stack trace to see the exact line — that tells which variable to inspect.

A simple, robust approach that avoids manual stream juggling is to read the second file and append its text to the first, then load the combined text into the RichTextBox. For small/medium files this is straightforward:

string f1 = @"C:\Users\Fish\Desktop\fyp-coding\sample1.txt";
string f2 = @"C:\Users\Fish\Desktop\fyp-coding\sample2.txt";

if (File.Exists(f2))
{
    string part = File.ReadAllText(f2);
    // ensure separation between files if needed
    File.AppendAllText(f1, Environment.NewLine + part);
}

richTextBox1.Text = File.Exists(f1) ? File.ReadAllText(f1) : string.Empty;

Notes and troubleshooting tips:

  • Use using with StreamReader/StreamWriter if you stream large files to avoid high memory usage and to ensure disposal.
  • If AppendAllText or other helpers are unavailable in your project, the project’s target framework may be older — either change the target or use a StreamWriter opened in append mode.
  • Double-check control names and that InitializeComponent() runs before you access UI controls; that often causes a null control reference.
  • When debugging, inspect each variable at the line reported by the exception; that is the fastest way to find the exact null reference.

This ties to and suggestions about reading and appending files, but uses a minimal, safe pattern that keeps the UI update simple and reduces stream/locking mistakes.

Recommended Answers

All 13 Replies

i think your code does just that

but when i want to read the file which have the new contents, it gave me error.

WHAT error?
WHERE did it occur?
How do you expect us to give you an answer?
If you post something that is vague, hazy and not even a question but a sentence formulated as a statement?

i think your code does just that

the error always occur. "Object reference not set to an instance of an object." What is this mean ? how to correct it?

*my first file is come from the output of my program. My second file is i create myself.
i will upload my coding at here.

private void CLICK2_Click(object sender, EventArgs e) {
    string file1 = @"C:\Users\Fish\Desktop\fyp-coding\sample1.txt";
    string file2 = @"C:\Users\Fish\Desktop\fyp-coding\sample2.txt";

    string[] lines = File.ReadAllLines(file2);
    File.AppendAllLines(file1, lines);

    myRichTextBox.Lines = File.ReadAllLines(file1);
}
private void CLICK2_Click(object sender, EventArgs e) {
    string file1 = @"C:\Users\Fish\Desktop\fyp-coding\sample1.txt";
    string file2 = @"C:\Users\Fish\Desktop\fyp-coding\sample2.txt";

    string[] lines = File.ReadAllLines(file2);
    File.AppendAllLines(file1, lines);

    myRichTextBox.Lines = File.ReadAllLines(file1);
}

I try already but this line got error...."File.AppendAllLines(file1, lines);" i dont know how to solve??

What error did you get?

What error did you get?

this is the error.."Error 1 'System.IO.File' does not contain a definition for 'AppendAllLines' C:\Users\Fish\Desktop\FinalYear\WindowsFormsApplication10\ 399 18 WindowsFormsApplication10
"

It's part of the .Net 4.0 library, you need to upgrade :)

This error : "Object reference not set to an instance of an object" means you are not initializing correctly an object. It has "null" value.

Can you tell us at what line do you get this error?

private void button1_Click(object sender, EventArgs e)
        {
          
            //2)MERGE ALL TEXT FILES INTO 1
            string mydirpath = ("c:\\Transaction Rejections\\Unprocessed");
            string[] txtFileList = Directory.GetFiles(mydirpath, "*.*");
            StringBuilder strFile = new StringBuilder();
            StreamWriter outfile = new StreamWriter("c:\\Transaction Rejections\\Dump.txt");

            foreach (string txtName in txtFileList)
            {
                using (StreamReader sr = new StreamReader(txtName))
                {
                    outfile.WriteLine(sr.ReadToEnd());
                }
            }
            outfile.Close();

Try that

It's part of the .Net 4.0 library, you need to upgrade :)

Sorry. I have another question. If now, i want to save my second output into the first text file. Let say, my first output is save in the text file called File1.Now, i wan save my second output in the File1 without overwrite the first output inside the file..How to do that...??

Create the StreamWriter with "append" param set to true:

StreamWriter outfile = new StreamWriter("c:\\text.txt", true);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.