Click here to Skip to main content
16,017,954 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am saving image in database but m getting error when I return data
C#
public byte[] readfile(string FPath) {
        byte[] data;
        try {
            FileInfo FI = new FileInfo(FPath);
            long numbytes = FI.Length;
            FileStream fstream = new FileStream(FPath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fstream);
            data = br.ReadBytes(Convert.ToInt64(numbytes));
            fstream.Close();
        }
        catch (Exception ex) {
            MsgBox(ex.Message.ToString);
        }
        return data;
Posted
Updated 8-Apr-13 19:51pm
v2

1 solution

This is because of your try-catch statement. Your variable data is actually assigned, but not in the case when exception is thrown prior to assignment of the reference. In this case, the execution will reach the point of return data when it is not assigned, which is unacceptable.

The lame solution would be modification of the line of the declaration:
C#
byte[] data = null;


Now it will compile and pass the runtime, but — don't do it!

The really good solution would be: remove all the exception handling! Surprised? You are handling the exceptions too locally. You need to let it go. One rule about exceptions is: don't handle them often. You need to do it rarely in some point of code which I call "the points of competence", plus in one universal point way up the stack of each thread. In the case if the UI thread, such universal point should be the main event-oriented cycle. If this is System.Windows.Forms please see my past answers:
Error Logging and Screen Shot.[^],
Catching an Exception[^].

There is a fully analogous handling in WPF; if interested, please find it by yourself, or just ask me a follow-up question; I'll answer.

—SA
 
Share this answer
 
Comments
Mehdi Gholam 9-Apr-13 1:52am    
5'ed
Sergey Alexandrovich Kryukov 9-Apr-13 1:53am    
Thank you, Mehdi.
—SA
Gourav Sharma from Jammu 9-Apr-13 1:54am    
Thank You ...
Sergey Alexandrovich Kryukov 9-Apr-13 1:55am    
You are welcome.
Good luck, call again.
—SA
Maciej Los 9-Apr-13 1:55am    
+5

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