Click here to Skip to main content
15,940,430 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C# IDE: Visual Studio 2019, Windows10Pro
Code text attached to command button
p
C#
rivate void button21_Click(object sender, EventArgs e)
    {   
       string line = System.String.Empty;
       string s_sourse = System.String.Empty;
       bool b_beforeRead = false; 
       bool b_afterRead = false; 
       string s_begin = "Begin"; 
       string s_end = "End"; 
       bool b_begin = false;  
       bool b_end = false;  
       int i_begin = 0; 
       int i_end = 0; 
        try
        {
            StreamReader sr = new StreamReader(@"D:\Input_my.txt"); 
            StreamWriter sw = new StreamWriter("D:\\Out_my.txt", false, Encoding.UTF8); 
            line = sr.ReadLine();
            byte k = 0; // temporary for debug

            while (line != null)  
            {
               // k++; // temporary
               // //+if (k > 6) // read only the first 6 lines of the input file
               ////+  if (k > 17) // 15 lines were written to the output file, but there was no Exception
               // if (k > 18) // 0 lines were written to the output file, Exception was
               //     goto Close_my;

                if ((line.Trim().Length == 0)) 
                    goto label_read;
    
             b_begin = line.Contains(s_begin);  
             b_end = line.Contains(s_end); 

                if (b_begin && b_end) 
                {
                    i_begin = line.IndexOf(s_begin); 
                    i_end = line.IndexOf(s_end); 
                    s_sourse = line.Substring(0, i_begin); 
                    MessageBox.Show("in line found 'Begin' and 'End'\n" + line);
                    goto label_wr;
                }  
                else
                {
                    s_sourse = line; 
                    goto label_wr;
                }
             goto label_read;
                
           label_wr:
                sw.WriteLine(s_sourse);
           label_read:
                b_beforeRead = line.Contains(s_begin);
                line = sr.ReadLine();
                b_afterRead = line.Contains(s_end); 
            }  // end  while (line != null) 
         Close_my:
            MessageBox.Show("Does it get here?" + s_sourse); 
            sr.Close();
            sw.Close();
         }  // end try
        catch (Exception e1)
        {
            MessageBox.Show("2.1 Exception: " + e1.Message);
        }   
        finally
        {
            MessageBox.Show("3.Executing finally block.");
        }
    }   // end button21
 } 
}


What I have tried:

Quote:
help fix this message
Posted
Updated 30-Mar-22 1:00am
Comments
CPallini 30-Mar-22 5:14am    
This is very common message. Your code is probably calling a method using a null reference instead of an object instance. You should post all the details of the error message in order to get better help.
Member 15583139 1-Apr-22 4:57am    
All the details of the message are in my project, which, as I understand it, cannot be sent to your forum, www.codeproject.com. I can only indicate my email, and those who want to help, their own, then you can send both the project and the details.
Richard MacCutchan 30-Mar-22 6:28am    
How about telling us which line the error occurs on? And using goto statements is very bad form.
Member 15583139 30-Mar-22 8:32am    
To clarify the issue, I can send my WFA_ReadLine_WriteLine.rar in which there is my test project containing one command button, to which the given text is attached, the input file Input_my.txt , but I do not know how to do this on the site www.codeproject.com
#realJSOP 31-Mar-22 6:34am    
Nobody here is going to download a RAR file. Run it in the debugger, and it will stop on the line that's throwing the exception. At that point, you will probably immediately see which variable is the problem.

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
Comments
CPallini 30-Mar-22 7:32am    
5.
First, DO NOT USE GOTO! There's absolutely NO REASON the code you posted needs to have GOTO statements. Write proper code. I haven't used a GOTO since 1978. It's a hold-over from interpreted basic, and should be avoided at all costs.

Second, here's my version of your method (assuming I have correctly determined what you're trying to do).

private static void button21_Click(object sender, EventArgs e)
{   
    string        line        = string.Empty;
    StringBuilder text        = new StringBuilder();
    List<string>  fileContent = new List<string>();
    int           lineCounter = 0;

    try
    {
        // "using" will initialize, and more importantly, finalize/cleanup 
        // file i/o automagically, allowing the programmer to concentrate 
        // on the actual purpose of the code. Notice there are no "Close"
        // statements, and more importantly, no "GOTO" statements. Another 
        // aspect is that this code is MUCH easier to read.

        // open the input file, and read the contents into a string list. This 
        // mitigates the possibility of throwing an exception during the read 
        // process, and also allws us to determine ahead of time whether we 
        // can ignore the operation because the file is empty.
        using (StreamReader sr = new StreamReader(@"c:\temp\Input.txt"))
        {
            // Read the entire file into a string list to avoid thrashing the 
            // hard drive. Change new line charachters ("\r\n") to a single 
            // character ("\n"), and then split the text on the single 
            // character.
            fileContent.AddRange(sr.ReadToEnd().Replace("\r\n", "\n").Split('\n'));
        }

        if (fileContent.Count > 0)
        {
            // your original code was difficult to read this early in the morning, 
            // but it appears as if you want to read lines from the source file until 
            // you've either read 6 lines, or until the last line read contains the 
            // word "End".

            // read the lines we want into a StringBuilder object. 
            do
            {
                line = fileContent[lineCounter];
                text.AppendLine(line);
                lineCounter++;
            } while ((lineCounter < fileContent.Count) && 
                     (lineCounter <= 5      || 
                      line.Contains(" End") || 
                      line.Trim().StartsWith("End")));

            using (TextWriter sw = File.CreateText(@"c:\temp\Output.txt"))
            {
                // now that we have our text, we can write all of it all at once.
                sw.Write(text.ToString());
            }
        }
    }
    catch (Exception ex)
    {
        // if a problem happens, we display the exception message, as well as the stack 
        // trace (the stack trace poitns to the code that failed).
        string error = string.Concat(ex.Message, 
                                     Environment.NewLine, 
                                     Environment.NewLine, 
                                     ex.StackTrace);
        //MessageBox.Show(error);
        Console.WriteLine(error);
    }
    // because the "using" statements above clean up for us, there's no reason to have 
    // a "finally" block. Also, all of the objects go outr of scope, so the memory they 
    // consumed is freed up.
} 
 
Share this answer
 
v4
Comments
CPallini 30-Mar-22 7:32am    
5.
Member 15583139 30-Mar-22 8:52am    
Goto - I know, but that's no reason not to. The code text I provided processed 5000 lines in the input file without this message, but this message appears on some files. I have prepared a test project to help those who wish to understand the reason not to spend a lot of their personal time, but to immediately get to the heart of the problem. There are also 19 lines in the input file where the Exception appears. How to deliver WFA_ReadLine_WriteLine.RAR to you? I HOPE there are no viruses.
Chris Copeland 30-Mar-22 9:16am    
Goto - I know, but that's no reason not to. -- there absolutely is a reason not to. Modern developers do not use these semantics, so it's better to understand from the start that you shouldn't be using them. If you decided to join an open source project, or start your own, or tried to get a job in a development role, and you were using goto as part of your development then there's a good chance you'd be in trouble.

Aside from that, it also makes code more difficult to read than it needs to be. With appropriate if, while and return/break/continue statements and correct indentation, code becomes much easier to read. Remember that while it might seem an okay practise for yourself to use, asking for help on code which is difficult to read isn't likely to trigger many responses -- aside from the one you've already seen: "Don't use goto"

Just my two cents, you can take it or leave it. I recommend you do move away from using goto when developing code however.
Dave Kreskowiak 30-Mar-22 9:31am    
No reason? Goto encourages difficult to read "spaghetti code." That's why nobody uses it.

Nobody but you can run the code with the dataset you're using. YOU are the only person who is going to be able to figure out why your code isn't properly dealing with the data in some files.

This isn't going to be because of some virus.
#realJSOP 31-Mar-22 8:32am    
I updated my answer to fix a couple of small problems and to segregate the reading and writing to make it more debuggable.

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