Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Hi , my code is

C#
FileStream stream = new FileStream("c:\aaa.jpg",FileMode.OpenOrCreate);


it works fine but my file at destination will be a blank file . which is aaa.jpg will be blank .

my full code is :

C#
string fileName = Path.GetFileName(File_Upload.PostedFile.FileName);
        string path = (ConfigurationManager.AppSettings["virtual_path"]).ToLower();

        Btn_upload.Enabled = false;
        File_Upload.Enabled = false;

        try
        {
            con.Open();
            SqlCommand cmdInsert = new SqlCommand("insert into tbl_Img (Fld_Uploader,Fld_path,Fld_mode) values ('admin','" + path + "','aaa')", con);
            cmdInsert.ExecuteNonQuery();

            SqlCommand cmdSelect = new SqlCommand("select top 1 * from tbl_Img order by Fld_id desc ", con);
            SqlDataAdapter da = new SqlDataAdapter(cmdSelect);
            DataTable dt = new DataTable();

            da.Fill(dt);
            
            ImgId = dt.Rows[0]["Fld_id"].ToString();
            RandCode = dt.Rows[0]["Fld_RandCode"].ToString();
            ImgName = ImgId + "_" + fileName;

            path = path + ImgId + "_" + fileName;

            string aaa = Server.MapPath("~/" + path);


            FileStream stream = new FileStream(aaa,FileMode.OpenOrCreate);

           // StreamWriter str = new StreamWriter(aaa);
            Response.Write(aaa);

            stream.Close();
            //File_Upload.PostedFile.SaveAs(Server.MapPath(stream.ToString()));

            SqlCommand cmdUpdate = new SqlCommand("update tbl_Img set Fld_FileName = '" + ImgId + "_" + fileName + "' where Fld_id = '" + ImgId + "' ", con);
            cmdUpdate.ExecuteNonQuery();


            con.Close();

            Img.ImageUrl = "../../ReadAttachment.aspx?code=" + RandCode + "&maxWidth=100&maxHeight=100";
        }
        catch (Exception ex) 
        {
            ErrorDiv.Attributes["class"]="ErrorDivVisible";
            array[count++] = "مشکلی در آپلود فایل وجود دارد";
            array[count++] = ex.Message;
            flag = 1;
            UlFunction(count, array);
        }

        BtnDelete.Visible = true;
        btnAdd.Enabled = true;
    }
Posted
Comments
Richard Deeming 14-Oct-14 13:46pm    
Your code is susceptible to SQL Injection[^].

NEVER use string concatenation to build a SQL query. ALWAYS use parameterized queries.
Sergey Alexandrovich Kryukov 14-Oct-14 14:13pm    
You are right. I explained it in detail in Solution 1, credited your comment, of course.
—SA
Sergey Alexandrovich Kryukov 14-Oct-14 14:09pm    
Why would you try to open a JPEG file?
—SA

Hi Member,

Is this "Copy-Paste" code?

 FileStream stream = new FileStream(aaa,FileMode.OpenOrCreate);

// StreamWriter str = new StreamWriter(aaa);
 Response.Write(aaa);

 stream.Close();


how about writing to the FileStream instead of the Response stream - you are opening the stream and close it. So no wonder the File is empty...

From your code it seems you miss some C#/programming "basics". I can just give you some general "advices".
Split your code into logical units - mixing up UI, data access and your buissness logic is not a good idea.
Your code is vulnarable to SQL injection too - and no, protecting against this is NEVER optional!

What can help to "sort your thoughts" is: Write first down what steps you have to do (e.g. as comments), fill it up with the code after that - you may can "see" then what "functions" - methods you have to implement without mixinig up things which don't belong together - and handle specific Errors to each Operation - your current code catches all exceptions - I can think of hundreds of things which could go wrong this code...
Example:

// Obtain File Path
// Insert Data
// Query for Data
// Save data into file
// Present your data

Just my 2cent...
Kind regards
Johannes
 
Share this answer
 
Comments
BillWoodruff 14-Oct-14 15:07pm    
+5 Very good advice written in a very clear way !
Member 11125813 14-Oct-14 15:51pm    
Thank you for your advice but whatever i copied is whatever i was testing . my main question is how to work and copy any file using filestream . i just need any simple sample or example for it . but anyway thanks for your advise .
johannesnestler 15-Oct-14 3:42am    
So the number one source for such things is MSDN - how about http://msdn.microsoft.com/de-de/library/system.io.filestream(v=vs.110).aspx - or just hit F1 in VisualStudio while Cursor/Focus is on FileStream... Does this sample there help?
It's not clear why would you try to open a JPEG file.

As to the SQL statement, you are doing it wrong. Richard Deeming is absolutely right; please see his comment to the question.

The statement is composed by concatenation with strings taken from UI. Not only repeated string concatenation is inefficient (because strings are immutable; do I have to explain why it makes repeated concatenation bad?), but there is way more important issue: it opens the doors to a well-known exploit called SQL injection.

This is how it works: http://xkcd.com/327[^].

What to do? Just read about this problem and the main remedy: parametrized statements: http://en.wikipedia.org/wiki/SQL_injection[^].

With ADO.NET, use this: http://msdn.microsoft.com/en-us/library/ff648339.aspx[^].

Please see my past answers for some more detail:
EROR IN UPATE in com.ExecuteNonQuery();[^],
hi name is not displaying in name?[^].

—SA
 
Share this answer
 
Comments
BillWoodruff 14-Oct-14 15:06pm    
+5 This answer did not deserve a vote of #1 !
Sergey Alexandrovich Kryukov 14-Oct-14 16:03pm    
Agree. :-) Thank you, Bill.
—SA

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