Assignment inside IF statement - c#

string Newfilename;
string Defaultfilename;
protected void btnup_Click(object sender, EventArgs e)
{
if (ASPxUploadControl1.HasFile)
{
string fileExt =
Path.GetExtension(ASPxUploadControl1.FileName);
if (fileExt == ".xls" || fileExt == ".xlsx")
try
{
string extension = Path.GetExtension(ASPxUploadControl1.FileName);
string id = Guid.NewGuid().ToString();
string fileLocation = string.Format("{0}/{1}{2}", Server.MapPath("upload/"), id, extension);
ASPxUploadControl1.SaveAs( fileLocation );
StatusLabel.Text = "Upload status: File uploaded!";
Newfilename = fileLocation;
Defaultfilename = Path.GetFileName(ASPxUploadControl1.FileName);
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
else
{
StatusLabel.Text = "Please choose excel file";
}
}
}
I am trying to assign values to Newfilename and Defaultfilename (inside "try", after naming uploaded file), but they stay empty.
Where I'm wrong?

Refactor your code and think about the process that you want .. then Debug the Code.. Test it.. and if you have an Issue then edit your post.. that's what I suggest..
If statements should be wrapped with in a code block "{ }" same way that you have Try {} a good rule of thumb for even readability would be to wrap everthing around {} if you have If Else otherwise it makes if hard to read as well as lend assistance.
inside your code where you are declaring the following, make them variables within the method itself
string fileExt = string.Empty;
string extension = string.Empty;
string id = string.Empty;
string fileLocation = string.Empty;
so your method would look like this
protected void btnup_Click(object sender, EventArgs e)
{
string fileExt = string.Empty;
string extension = string.Empty;
string id = string.Empty;
string fileLocation = string.Empty;
if (ASPxUploadControl1.HasFile)
{
fileExt = Path.GetExtension(ASPxUploadControl1.FileName);
if (fileExt == ".xls" || fileExt == ".xlsx")
{
try
{
extension = Path.GetExtension(ASPxUploadControl1.FileName);
id = Guid.NewGuid().ToString();
fileLocation = string.Format("{0}/{1}{2}", Server.MapPath("upload/"), id, extension);
ASPxUploadControl1.SaveAs( fileLocation );
StatusLabel.Text = "Upload status: File uploaded!";
Newfilename = fileLocation;
Defaultfilename = Path.GetFileName(ASPxUploadControl1.FileName);
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
else
{
StatusLabel.Text = "Please choose excel file";
}
}
}

Path.GetExtension returns null if the passed value is null and returns string.Empty if the passed value doesn't have an extension.
So please check if the value inside ASPxUploadControl1.FileName actually contains something usefull.
If this is not the case then you'll have to look up where the value is set and debug from there to find out why it's not set.

Can you step through the execution?
Does
NewFilename = fileLocation;
get executed?
If so, what are the values for NewFilename before and after?
This looks like ASP.Net code.
If it is. Is the problem that when you try to use NewFilename elsewhere in the code-behind is is blank.
If you are, then NewFilename may need to be saved to the session to allow you to use it.
hth,
Alan.

Related

How to change the name of a image from a textbox and save it into a folder?

I'm a beginner to the c# language.i just tried some code to save an image in to a folder.but i just wanna change the name of the image using a textbox text and save it to a folder.plese help me!! this is my code..
string appPath = Path.GetDirectoryName(Application.ExecutablePath) +
#"\IMAGES_DB\";
if (Directory.Exists(appPath) == false)
{
Directory.CreateDirectory(appPath); }
if (opFile.ShowDialog() == DialogResult.OK)
{
try
{
string iName = opFile.SafeFileName;
string filepath = opFile.FileName;
File.Copy(filepath, appPath + iName);
pictureBox2.Image = new Bitmap(opFile.OpenFile());
}
catch (Exception exp)
{
MessageBox.Show("Unable to open file " + exp.Message);
}
}
else
{
opFile.Dispose();
}
Well this answer is kinda asked here: Rename a file in C#
So basically use something like this:
System.IO.File.Move("oldfilename", "newfilename");
In your case:
string appPath = Path.GetDirectoryName(Application.ExecutablePath) +
#"\IMAGES_DB\";
if (!Directory.Exists(appPath)) {
Directory.CreateDirectory(appPath);
}
if (opFile.ShowDialog() == DialogResult.OK) {
try {
string iName = opFile.SafeFileName.Text;
string filepath = opFile.FileName.Text;
File.Move(filepath, appPath + iName);
} catch (Exception exp) {
MessageBox.Show("Unable to open file " + exp.Message);
}
}

ASP.Net FileUpload: Rename file name before saving if already exists

I need change file name when users upload from file upload control.
If file name be duplicate it add count at file name but here it doesn't work.
I mean when I upload file i.e. 00076007-2013.pdf it saves in the host with this name 00076007-2013(0).pdf
But when again I want upload 00076007-2013.pdf in host it overwrite last (00076007-2013(0).pdf).
But I want if there was 00076007-2013.pdf file it saves with this name 00076007-2013(1).pdf in host.
How I can solve this problem.
My code below.
int count = 0;
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string FileExstention = Path.GetExtension(FileUpload1.FileName);
string[] files = Directory.GetFiles(Server.MapPath("/public/2Version/sk_PDF/"));
if (FileUpload1.HasFile)
{
if (FileExstention == ".pdf")
{
try
{
if (File.Exists(Server.MapPath("/public/2Version/sk_PDF/") + fileName.ToString()))
{
foreach (string s in files)
{
string filename = string.Empty;
filename = Path.GetFileName(s).Substring(0, Path.GetFileName(s).LastIndexOf("."));
if (filename.Contains("("))
{
filename = filename.Substring(0, filename.LastIndexOf("("));
}
if (filename == fileName.ToString().Trim())
{
count++;
}
FileUpload1.PostedFile.SaveAs(Server.MapPath("/public/2Version/sk_PDF/") + filename.ToString() + "(" + count.ToString() + ")" + FileExstention);
}
}
else
{
FileUpload1.PostedFile.SaveAs(Server.MapPath("/public/2Version/sk_PDF/") + fileName.ToString());
}
}
catch (Exception ex)
{
throw ex;
}
}
}
Edit #01
This is the output.
I have upload the 00076007-2013.pdf file for three times.
The first time OK, 00076007-2013.pdf.
The second time OK, 00076007-2013(0).pdf.
The last time he was saved 00076007-2013(0).pdf and not 00076007-2013(1).pdf
Please change this part :
if (filename.Contains("("))
{
filename = filename.Substring(0, filename.LastIndexOf("("));
}
With :
if (filename.Contains("("))
{
filename = filename.Substring(0, filename.LastIndexOf("("));
count++;
}
I hope I was helpful.

Uploaded file not being saved to directory

I am trying to upload a file using devexpress save as function which works exact same as the standard asp.net uploader but i am getting the following error
Could not find a part of the path 'C:\Projects\fhs\fhs\Uploads\documents\VX00150\Barry Allen\Aperture - Signature Template.docx'.
UploadDirectory refers to a virutal directory setup in the web config which im getting via the property.
string UploadDirectory = WebConfigurationManager.AppSettings["uploadDirectory"].ToString();
Which contains the directory
<add key="uploadDirectory" value="~\Uploads\" />
But for the live of me I cannot see why the file is not saving to the server
protected void UploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
{
UploadControl.Enabled = false;
string id = Request.QueryString["Case"];
if (id != null)
{
CaseId = Guid.Parse(id);
OpenCase = _dal.GetCaseById(Guid.Parse(id));
}
string PersonId = Session["CurrentPersonalMainID"].ToString();
Personal = _dal.GetPersonalByPersonalId(new Guid(PersonId));
e.CallbackData = SavePostedFile(e.UploadedFile, OpenCase.CaseReference, Personal.firstName, Personal.lastName);
}
The below saved postedfile is called from above
public string SavePostedFile(UploadedFile uploadedFile,string IVACaseRef, string firstName ,string lastName)
{
try
{
if (!uploadedFile.IsValid)
return string.Empty;
string fileName = uploadedFile.FileName;
FileInfo fileInfo = new FileInfo(uploadedFile.FileName);
string fullFileName = CombinePath(fileName);
string docsPath = UploadDirectory + #"documents\" + IVACaseRef + #"\" + firstName + " " +
lastName + #"\";
string resFileName =docsPath + fileInfo.Name;
bool exists = System.IO.Directory.Exists(resFileName);
if (!exists)
System.IO.Directory.CreateDirectory(docsPath);
uploadedFile.SaveAs(Server.MapPath(resFileName), true);
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(resFileName.ToString());
// we need to reget this as issue with postback and the fileuplaod
FormsIdentity _identity = (FormsIdentity)Context.User.Identity;
_identity = (FormsIdentity)Context.User.Identity;
return fileName;
}
catch (Exception ex)
{
string inner = string.Empty;
if (ex.InnerException != null)
{
inner = ex.InnerException.ToString();
}
// logger.Error("Error in GetNotificationById function aperturenetdal " + ex.ToString() + " " + inner);
return "";
I've noticed that a lot of file manipulation methods and classes differ in how they handle spaces, sometimes in ways that are not well documented. For example, I've seen situations where testing for the existence of a file with a space in the filename succeeds but opening it does not.
It's just a hunch, but it seems likely.

Files on the server are overwritten with files of the same name

I am trying to upload files with same names to the server using GUID, but its not working and is still replacing the old files, can anybody help me by telling where I am making the mistake?
here is y code to upload:
protected void btnAddExpenditure_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
//check file Extension & Size
int filesize = FileUpload1.PostedFile.ContentLength;
if (filesize > (20 * 1024))
{
Label1.Text = "Please upload a zip or a pdf file";
}
string fileextention = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileextention.ToLower() != ".zip" && fileextention.ToLower() != ".pdf")
{
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "Please upload a zip or a pdf file";
}
else
{
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//save file to disk
FileUpload1.SaveAs(Server.MapPath("Reciepts/" + ReceiptFileName));
}
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Here's your problem. You're creating a new string variable that holds the file name (FileName). If it exists, you modify FileName with a new GUID. But at the very end...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
you're still using the original FileUpload1.PostedFile.FileName. This should be changed to
string ReceiptFileName = Path.GetFileName(FileName);
EDIT: Reading through the code again, I think you may have other problems as well. Assuming that FileUpload1.PostedFile.FileName is a full path (i.e. C:\Folder\File.txt), then
FileName = Guid.NewGuid() + FileName;
would result in something like 123-4321-GUIDC:\Folder\File.txt
I doubt that's what you want. You might want to flip that around
FileName = FileName + Guid.NewGuid();

How to check the existence of the file in this file upload function?

I am trying to develop upload file function with security as my programming instructor asked me to do. I implemented it in such a way that it will check the size, file format and the existence of the file. The logic was working well except for checking the existence of the file. For example, when I tried to upload a file which is already existed, I will not get a message telling me that the file is already existed and I don't know why it is not working.
protected void UploadFile(object sender, EventArgs e)
{
if(FileUpload1.HasFile)
try
{
string[] validTypes = { "bmp", "gif"};
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
if (size < limit)
{
for (int i = 0; i < validTypes.Length; i++)
{
if (ext == "." + validTypes[i])
{
string path = #"~\Images\";
string comPath = Server.MapPath(path + "\\" + FileUpload1.FileName);
if (!File.Exists(comPath))
{
FileUpload1.PostedFile.SaveAs(comPath);
Label1.Text = "File uploaded";
}
else
{
Label1.Text = "Existed";
}
}
else
{
Label1.Text = "Invalid File." + string.Join(",", validTypes);
}
}
}
else
{
Label2.ForeColor = System.Drawing.Color.Red;
Label2.Text = "file is heavy";
}
}
catch (Exception ex)
{
Label2.Text = "The file could not be uploaded. The following error occured: " + ex.Message;
}
}
When I debugged the code, I found that it will execute the else statement, but instead of displaying it to the user, it will display the message in the outer else statement which is "Invalid File.". Why?
if (ext == "." + validTypes[i])
{
string path = #"~\Images\";
string comPath = Server.MapPath(path + "\\" + FileUpload1.FileName);
if (!File.Exists(comPath))
{
FileUpload1.PostedFile.SaveAs(comPath);
Label1.Text = "File uploaded";
}
else
{
Label1.Text = "Existed";
}
}
else
{
Label1.Text = "Invalid File." + string.Join(",", validTypes);
}
Also, my instructor told me that the following line causes a vulnerability called path traversal.
string path = #"~\Images\";
So how to prevent this security hole? ?Any ideas?
There is logical problem in you code.In the block
for (int i = 0; i < validTypes.Length; i++)
It will always run two time for each file.
What you can do you take a Boolean variable at set it to false.
Go inside the loop and if file found set boolean to true and use break statement.
At the end of loop check for the Boolean value and code accordingly.
Edit-1
Rather than looping through the array you can use like this
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos >- 1)
{
// the array contains the string and the pos variable
// will have its position in the array
}
In your case
string[] validTypes = { "bmp", "gif"};
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
int pos = Array.IndexOf(validTypes , ext );
if(pos>=0)
{
string path = #"~\Images\";
string comPath = Server.MapPath(path + "\\" + FileUpload1.FileName);
if (!File.Exists(comPath))
{
FileUpload1.PostedFile.SaveAs(comPath);
Label1.Text = "File uploaded";
}
else
{
Label1.Text = "Existed";
}
}
else
{
Label1.Text = "Invalid File." + string.Join(",", validTypes);
}

Categories