image in current folder not deleted upon new upload - c#

Ok new problem this is my full code I will explain what I'm trying to do and segment each part so you can see what it is I'm trying to achieve:
Full Code:
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=x; Password=x;");
cn.Open();
OdbcCommand sc = new OdbcCommand(string.Format("SELECT picturepath FROM Pictures WHERE UserID ='{0}'", theUserId), cn);
OdbcDataReader reader = sc.ExecuteReader();
while (reader.Read())
{
if (System.IO.File.Exists(Convert.ToString(reader[0])))
{
System.IO.File.Delete(Convert.ToString(reader[0]));
}
}
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId +
"/uploadedimage/") +
Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") +
filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "','" + fileuploadpaths + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
Ok the first part I'm trying to do is select the picture path related to the userid then if a userid is there with the same userid as im trying to upload delete the file that exists(not stored in database hence the IO) this part doesn't work the file pathname of the current userid isn't being deleted.
OdbcCommand sc = new OdbcCommand(string.Format("SELECT picturepath FROM Pictures WHERE UserID ='{0}'", theUserId), cn);
OdbcDataReader reader = sc.ExecuteReader();
while (reader.Read())
{
if (System.IO.File.Exists(Convert.ToString(reader[0])))
{
System.IO.File.Delete(Convert.ToString(reader[0]));
}
}
The second part just inserts the new file upload path and name into my database related to the current userid (this works) the file is uploaded to the correct folder and its inserted into my database. I could change this to UPDATE rather than insert but atm its either or not to fussy.
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId +
"/uploadedimage/") +
Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") +
filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "','" + fileuploadpaths + "')", cn);
cmd.ExecuteNonQuery();
So my problem is why is my if statement not deleting the currently held record in my database for the path of the current image? All that happens is my new image is uploaded into the same folder but the old image still remains?
Remember though I'm not trying to delete the "same" file name a simple saveas would overwrite it which is already in my code, what I need is for my code to delete any image that is currently in the userid specific folder when I'm trying to save the new image upload.
Any thoughts some help on the code?
Thanks guys

Looking at your code, I believe SystemDown has the answer in the comments:
When you save the file to disk you use the following code:
// Even though you've just calculated the result of Path.GetFileName you
// redo it here?
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId
+ "/uploadedimage/")
+ Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
Then you store it in the DB as:
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") +
filenameDB;
However when you delete the file you're not performing Server.MapPath:
System.IO.File.Delete(Convert.ToString(reader[0]));
Change that line to:
System.IO.File.Delete(Server.MapPath(Convert.ToString(reader[0])));
And it should all work.

you should use the server.mappath to find that if image is already exist or not then try to delete that im

Related

How to upload a DB backup to a FTP server

On the tail end of database backup project and I've run into a issue where the Deflate compression I put in can't seem to find the path I saved the backup to. Being that the default backup location (used here) is on a network drive is there something else I need to do to make sure the path is found by Deflate? As of now I get System.IO.DirectoryNotFoundException: 'Could not find a part of the path. The purpose of the tool is to be able to put in any server you want to access, get a list of available DB's and then choose the one you want to backup.
I had this issue before locally, but all i had to do was give SQLserver the proper permissions to the folder.
using (SqlConnection newConn = new SqlConnection(connString))
using (SqlCommand sqlCmd = new SqlCommand(query, newConn))
{
newConn.Open();
value = sqlCmd.ExecuteScalar();
canCompress = !(value == null || Convert.ToInt32(value) == 0);
//----------------------------------
//SQL Commands to run backup process
//----------------------------------
Interface.WriteLine("Creating backup");
if (canCompress)
{
sqlCmd.CommandText = "BACKUP DATABASE [" + connBuilder.InitialCatalog + "] "
+ "TO DISK = '" + backupFile + "' "
+ "WITH COPY_ONLY, COMPRESSION, NOFORMAT, NOINIT, "
+ "NAME = '" + backupName + "', "
+ "SKIP, REWIND, NOUNLOAD, STATS = 10";
sqlCmd.ExecuteNonQuery();
}
else
{
sqlCmd.CommandText = "BACKUP DATABASE [" + connBuilder.InitialCatalog + "] "
+ "TO DISK = '" + backupFile + "' "
+ "WITH COPY_ONLY, NOFORMAT, NOINIT, "
+ "NAME = '" + backupName + "', "
+ "SKIP, REWIND, NOUNLOAD, STATS = 10";
sqlCmd.ExecuteNonQuery();
}
//----------------------------------
//Grab Backup File
//----------------------------------
query = "SELECT physical_device_name "
+ "FROM msdb.dbo.backupset b "
+ "JOIN msdb.dbo.backupmediafamily m ON b.media_set_id = m.media_set_id "
+ "WHERE database_name = '" + connBuilder.InitialCatalog + "' "
+ "ORDER BY backup_finish_date DESC ";
using (SqlConnection connection = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
value = cmd.ExecuteScalar();
if (value != null)
backupFile = (string)value;
else
throw new Exception("Unable to find backup file.");
}
//Set which files should be uploaded.
if (canCompress)
{
fileToUpload = backupFile;
}
else
{
fileToUpload = Deflate.CompressFile(backupFile); //Point of error message
File.Delete(backupFile);
}
return fileToUpload;
}
static class Deflate
{
public static string CompressFile(string sourcePath, string destPath = null)
{
if (destPath == null)
destPath = Path.Combine(Path.GetDirectoryName(sourcePath), Path.GetFileNameWithoutExtension(sourcePath) + ".cmp");
using (FileStream originalFileStream = File.OpenRead(sourcePath))
using (FileStream compressedFileStream = File.Create(destPath))
using (DeflateStream compressionStream = new
DeflateStream(compressedFileStream, CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
compressedFileStream.Flush();
}
FileInfo sourceInfo = new FileInfo(sourcePath); //Remove the .bak extension on compression?
FileInfo destInfo = new FileInfo(destPath); //Remove the .bak extension on compression?
Console.WriteLine("Compressed {0} from {1} to {2} bytes.", Path.GetFileName(sourcePath), sourcePath.Length, destInfo.Length);
return destPath;
}
}

Upload text, image to database using textBox and fileUpload

Greeting All
I'm trying to create an asp.net webpage using C# to Upload a details about products containing Product name, description, image and Product Number.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string path = Server.MapPath("ProductsImages/");
if (FileUpload1.HasFile)
{
string ext = Path.GetExtension(FileUpload1.FileName);
if (ext == ".jpg" || ext == ".png")
{
FileUpload1.SaveAs(path + FileUpload1.FileName);
string name = "~/ProductsImages/" + FileUpload1.FileName;
string s = " insert into Products values('" + txtProductName.Text.Trim() + txtDescription.Text.Trim() + txtPrice.Text.Trim() + txtProductNumber.Text.Trim() + "','" + name + "')";
SqlCommand cmd = new SqlCommand(s, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Your File Has Been Uploaded");
}
else
{
Response.Write("You can upload only Jpg and png file");
}
}
else
{
Response.Write("Please Select an file To upload");
}
}
but when I start debugging it shows me an error : SqlException :
column name or number of supplied values does not match table definition.
However, my database design :
Column Name | Data type
Name nvarchar(50)
Description nvarchar(50)
Price nvarchar(50)
Image image
Product_Number nvarchar(50)
I don't know where is the wrong, in code or database??
Put a breakpoint on the line that you are creating your SQL Command. When the breakpoint is hit, inspect the value of the variable s. Your problem will become apparent: all you're doing is concatenating several of your fields into one single string. If you split them correctly, it should work.
On the other hand, you shouldn't be building your queries like that anyway. Use SqlParameters to correctly build and escape your queries.
Your insert query is missing commas.
It should be:
string s = " insert into Products values('" + txtProductName.Text.Trim() + "', '" + txtDescription.Text.Trim() + "', " + txtPrice.Text.Trim() + ", " + txtProductNumber.Text.Trim())";
It would be better to do it with SqlParameters, though. Here's how I'd do it:
var queryInsert = "Insert Into Products Values (#productName, #productDescription, #productPrice, #productNumber)";
cmd.Parameters.AddWithValue("#productName", txtProductName.Text.Trim());
cmd.Parameters.AddWithValue("#productDescription", txtDescription.Text.Trim());
...you get the idea. You'd set up the parameters for each of them like I did above.

fileupload isnt creating folder if its not there

My fileupload isnt creating the path if its not there, its only working if the folder belonging to the user id is actually already in place, I need it to upload whether the folder is there or not.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
string filenameDB = Path.GetFileName(FileUpload1.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") + filenameDB;
Label2.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES (" + theUserId + ", '" + fileuploadpaths + "')", cn);
cmd.ExecuteNonQuery();
OdbcCommand md = new OdbcCommand("UPDATE User SET flag = 0 WHERE UserId = '" + theUserId + "'", cn);
// OdbcCommand cmd = new OdbcCommand("UPDATE Pictures SET picturepath ='" + fileuploadpaths + "' WHERE UserId = '" + theUserId + "'", cn);
md.ExecuteNonQuery();
Response.Redirect("UserProfileWall.aspx");
}
catch (Exception ex)
{
Label2.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
Why don't you simply check if the folder is already created, if it's not create it. if(System.IO.Directory.Exists("YourDirectoryPath")) do your stuff;
The command you want to utilize is
string fileuploadDir = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/");
if(!System.IO.Directory.Exists(fileuploadDir)
{
System.IO.Directory.CreateDirectory(fileuploadDir)
}
Insert this after:
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUpload1.FileName);
Corrected based on comments below.
string dirPath= Path.GetDirectoryName(fileuploadpath);
if(!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}

strange string format + pathname from fileupload in mysql

Hey guys I have a problem im uploading images to my project path the images are contained within ~/userdata/UserID/uploadedimage/image.jpg
I used the below method to upload and to store the path of the picture in my database.
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
//string filename = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
What I found is the path isnt the path of my project directory its something strange:
Here is a snippet from my database the first one idPictures = 1 is the correct path name I need.
idPictures = 2 is the one that the fileupload is inserting into my database?
How can I get it so it will give a path name like this:
~/userdata/2/uploadedimage/batman-for-facebook.jpg
Edit:
If I try this:
string fileuploadpath = ("~/userdata/"+theUserId+"/uploadedimage/")+Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('"+theUserId+"','"+fileuploadpath+"')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
I get the error:
The file could not be uploaded. The following error occured: The SaveAs method is configured to require a rooted path, and the path '~/userdata/1/uploadedimage/holypally.jpg' is not rooted.
I suspect it's treating backslashes as escape characters in your SQL statement. Don't forget, you're using Server.MpaPath - i.e. you're trying to find the Windows absolute filename for the file.
This is exactly the kind of thing that happens when you don't use parameterized SQL statements, but instead include what is essentially user-specified text into your SQL directly. Don't do that. Use a parameterized SQL command, specify the values separately and then you at least won't need to worry about wonky values.
Of course, you'll still need to work out whether you really wanted to store the translated path or not, but that's a different matter.
In order to answer my own question I had to create two strings one purely for fileupload and the other purely for database pathname storage:
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/")+Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/"+theUserId+"/uploadedimage/")+filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('"+theUserId+"','"+fileuploadpaths+"')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}

insert into multiple tables without knowing the primary key

Hey guys bit of a complication here, I have a create account page and it just inserts data into a mysql db:
protected void Button1_Click(object sender, EventArgs e)
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email, FirstName, SecondName, DOB, Location, Aboutme, username, password) VALUES ('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '" + TextBox7.Text + "', '" + TextBox8.Text + "')", cn);
cmd.ExecuteNonQuery();
{
//e.Authenticated = true;
Response.Redirect("Login.aspx");
// Event useradded is true forward to login
}
}
}
But here is my problem on the create account page I have added a fileupload control and I would like to upload a image and save the imageurl in the pictures table:
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") + filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures VALUES picturepath ='" + fileuploadpaths + "' WHERE UserId = '" + theuserid + "'", cn);
cmd.ExecuteNonQuery();
The first problem is the sql syntax I need to combine the fileupload with my buttonclick so it would be INSERT INTO two tables User and Pictures but the problem after that is how on earth do I get the userid if the account isnt created yet? AHHH lol
Table structure:
So to sum it up I need to Insert user details into the user table and upload to the project file AND insert the imageUrl into the pictures table (stored like so ~/userdata/2/uploadedimages/bla.jpg) as you can see the pictures table is a 1-1 relationship to the user table so its dependant on the userid which be4 the account is created there is no userid so not sure if there is a way to stagger the code so the user details are inserted first then use a session to retrieve that userid then insert the imageurl into the pictures table?
Or Maybe there is some funky function that some clever person has already came upon this issue or maybe its just a simple sql syntax decombobulator.
P.S I KNOW ABOUT THE SQL INJECTION RISKS, please do not post about this. Thanks guys!
EDIT:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email, FirstName, SecondName, DOB, Location, Aboutme, username, password) VALUES ('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '" + TextBox7.Text + "', '" + TextBox8.Text + "')", cn);
OdbcCommand sc = new OdbcCommand("SELECT LAST_INSERT_ID()", cn);
//convert LAST INSERT into string theUserId
string filenameDB = Path.GetFileName(FileUpload1.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") + filenameDB;
Label10.Text = "Upload status: File uploaded!";
OdbcCommand cm = new OdbcCommand("INSERT INTO Pictures (picturepath, UserId) VALUES ('" + fileuploadpaths + "', " + theUserId + ")", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Label10.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
//e.Authenticated = true;
//Response.Redirect("Login.aspx");
// Event useradded is true forward to login
}
}
}
If pictures is 1:1 with users, is it possible to put the picture path in the user table?
If not, MySQL has a last_insert_id() function allowing you to get the last auto-increment value from a table (in this case User) - usually the primary key.
You need to return the new user id from your user insert. From the mysql auto increment docs:
You can retrieve the most recent
AUTO_INCREMENT value with the
LAST_INSERT_ID() SQL function or the
mysql_insert_id() C API function.
These functions are
connection-specific, so their return
values are not affected by another
connection which is also performing
inserts.
Anyway, you'll need to store this return and pass it into related operations.
I can't see your table structure, but is it as simple as inserting into the User table, retrieving the UserID, preserving the UserID (maybe passing to the upload page on the query string, or using session, etc), and then using that UserID in the Pictures table insert? Here's documentation on how to get the unique ID from an inserted row in MySQL.

Categories

Resources