Why is File.exists (Filename) statement not working? - asp.net

This is my code
protected void btnAdd_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
switch(SubDrpDownList.SelectedIndex)
{
case 0:
if (!File.Exists(filename))
FileUploadControl.SaveAs(Server.MapPath("~/Books/Math/") + filename);
else if (File.Exists(filename))
{
throw new DuplicateWaitObjectException();
}
break;
case 1:
if (!File.Exists(filename))
FileUploadControl.SaveAs(Server.MapPath("~/Books/Physics/") + filename);
else if (File.Exists(filename))
{
throw new DuplicateWaitObjectException();
}
break;
case 2:
if (!File.Exists(filename))
FileUploadControl.SaveAs(Server.MapPath("~/Books/Drawing/") + filename);
else if (File.Exists(filename))
{
throw new DuplicateWaitObjectException();
}
break;
}
lblStatus.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
lblStatus.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
According to the category, I want books to be uploaded on diffrenet folder which i have achieved using switch statement. Problem is when i upload a book and then for the second time again upload it , File.Exists(filename) doesn't work. What I want is If i upload the same file twice, I want to throw an exception that duplicate file has been trying to be uploaded. But in case of case statement only line !File.Exists(filename)) gets executed even in case of duplicate file. Why is File.Exists(filename)) not getting executed??

The issue is that you are checking to see if the file exists based solely off of the filename, and not off of the full path to the file. What it should be is
protected void btnAdd_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
switch(SubDrpDownList.SelectedIndex)
{
case 0:
if (!File.Exists(Server.MapPath("~/Books/Math/") + filename))
FileUploadControl.SaveAs(Server.MapPath("~/Books/Math/") + filename);
else
{
throw new DuplicateWaitObjectException();
}
break;
case 1:
if (!File.Exists(Server.MapPath("~/Books/Physics/") + filename))
FileUploadControl.SaveAs(Server.MapPath("~/Books/Physics/") + filename);
else
{
throw new DuplicateWaitObjectException();
}
break;
case 2:
if (!File.Exists(Server.MapPath("~/Books/Drawing/") + filename))
FileUploadControl.SaveAs(Server.MapPath("~/Books/Drawing/") + filename);
else
{
throw new DuplicateWaitObjectException();
}
break;
}
lblStatus.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
lblStatus.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
This will account for the fact that where you are uploading the file is different than where you are checking the file exists
Also, the elseif just needs to be else, because it either exists or it doesn't so you don't need to check again that it exists, that is implied by the "else"

I think the problem you have is that you are reducing the full file name (with path) to just the file name here:
string filename = Path.GetFileName(FileUploadControl.FileName);
From that point !File.Exists is always true.
eg. you are reducing "C:\Somepath\myfile.txt" to "myfile.txt" then checking if it exists.

Related

IOException: The process cannot access the file 'filename' because it is being used by another process

I have this code in my asp.net project:
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
using (StreamWriter sw = File.CreateText(Server.MapPath(#"~/AboutUs.txt")))
{
sw.Write(FreeTextBox1.Text);
sw.Close();
sw.Dispose();
lblError.Text = "تغییرات با موفقیت ذخیره شد.";
lblError.CssClass = "success";
}
}
catch (Exception ex)
{
lblError.Text = "خطایی روی داده است!" + "\n" + ex.ToString();
lblError.CssClass = "error";
}
finally
{
lblError.Visible = true;
}
}
Sometimes (not always) when I hit btnSave following error is occurred:
IOException: The process cannot access the file 'filename' because it is being used by another process
Why?
You just Run your application after see windows task manager-->Processes, any notepad.exe running you just right click then click end process . .

Upload and Delete file by using File Upload Control asp.net

I am developing a complaint form. In this this form, I must make a function that uploads a file and then delete the file that was uploaded. I can upload a file to the server, but I can't take a link of the file I upload to the server in order to delete it. Please help me. Here is my code:
public string FilePath;
protected void btAdd_Click(object sender, EventArgs e)
{
if (AttachFile.HasFile)
{
try
{
string[] sizes = {"B", "KB", "MB", "GB"};
double sizeinbytes = AttachFile.FileBytes.Length;
string filename = Path.GetFileNameWithoutExtension(AttachFile.FileName);
string fileextension = Path.GetExtension(AttachFile.FileName);
int order = 0;
while (sizeinbytes >= 1024 && order + 1 < sizes.Length)
{
order++;
sizeinbytes = sizeinbytes/1024;
}
string result = String.Format("{0:0.##} {1}", sizeinbytes, sizes[order]);
string encryptionFileName = EncrytionString(10);
FilePath = "Path" + encryptionFileName.Trim() + AttachFile.FileName.Trim();
AttachFile.SaveAs(FilePath);
}
catch (Exception ex)
{
lbMessage.Visible = true;
lbMessage.Text = ex.Message;
}
}
}
protected void btDelete_Click(object sender, EventArgs e)
{
try
{
File file = new FileInfo(FilePath);
if (file.Exists)
{
File.Delete(FilePath);
}
}
catch (FileNotFoundException fe)
{
lbMessage.Text = fe.Message;
}
catch (Exception ex)
{
lbMessage.Text = ex.Message;
}
}
Each request in asp.net creates a new object of your Page.
If you set variables during one request, they will not be available on the next request.
Your delete logic seems to depend upon FilePath being set during upload. If you want the page to remember that, keep it in the ViewState. The ViewState is maintained across requests to the same page and that would allow you to use the variable FilePath during delete.
This can be easily achieved by making FilePath a property and getting it from the ViewState.
public string FilePath
{
get
{
return (string) ViewState["FilePath"];
}
set
{
ViewState["FilePath"] = value;
}
}
YOU SHOULD DO IT IN THIS WAY.
if (imgUpload.HasFile)
{
String strFileName = imgUpload.PostedFile.FileName;
imgUpload.PostedFile.SaveAs(Server.MapPath("\\DesktopModules\\Indies\\FormPost\\img\\") + strFileName);
SqlCommand cmd01 = new SqlCommand("insert into img (FeaturedImg) Values (#img)", cn01);
cmd01.Parameters.AddWithValue("#img", ("\\DesktopModules\\Indies\\FormPost\\img\\") + strFileName);
}
With this code you can upload file in a particular location in your sites root directory.
and the path will be stored in database as string.
so you can access the file just by using the path stored in database.
If you cant understand anything. or wanna know more u can contact me or ask me here in comments.

Browse and upload file

I have a ASP.NET (.NET Framework 3.5) Application. Now, I have to place a Button on a aspx-Page with the fallowing functionality on click:
Ask the user for a file with Extension xls (OpenFileDialog)
Upload the selected file to a specific folder on the WebServer
How can I do this?
Thanks for your help.
Here is the code that can be used for file upload after checking certain file types.
protected void Upload_File() {
bool correctExtension = false;
if (FileUpload1.HasFile) {
string fileName = FileUpload1.PostedFile.FileName;
string fileExtension = Path.GetExtension(fileName).ToLower();
string[] extensionsAllowed = {".xls", ".docx", ".txt"};
for (int i = 0; i < extensionsAllowed.Length; i++) {
if (fileExtension == extensionsAllowed[i]) {
correctExtension = true;
}
}
if (correctExtension) {
try {
string fileSavePath = Server.MapPath("~/Files/");
FileUpload1.PostedFile.SaveAs(fileSavePath + fileName);
Label1.Text = "File successfully uploaded";
}
catch (Exception ex) {
Label1.Text = "Unable to upload file";
}
}
else {
Label1.Text = "File extension " + fileExtension + " is not allowed";
}
}
}
You should start with the ASP.NET FileUpload control. Here is a pretty good tutorial on how to complete this task.

How to change fileupload name

im using following code to upload
protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~upload/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
I want to change the upload file name...I have to assign file name for every uploaded file how?
This line pickes up the the name of the uploaded file:
string filename = Path.GetFileName(FileUploadControl.FileName);
This line tells the server what to save the file as:
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
Simply change the value of filename to something else before saving.
there is a way to change the name of the file that we downloaded to our "~Server/Userfolder"(as an example)..
i was really thinking on renaming file before the .SaveAs command, which is gonna be like:
if (Request.Files != null)
{
var getmyfile = Request.Files["some_photo"];
try
{
if (getmyfile.FileName != "" && getmyfile.FileName != null && getmyfile.ContentLength > 0)
{
///Create Useruploads path.
var path = Server.MapPath("~/Useruploads" + "\\");
///Get file info that we gonna upload to server..
FileInfo TheFile = new FileInfo(path + Path.GetFileName(getmyfile.FileName));
///Note: i used Path.GetFileName(getmyfile.FileName) code cause getmyfile.FileName gives full path of that file..
if (TheFile.Exists)
{
///Seperate file name and extention..
var fname = Path.GetFileNameWithoutExtension(TheFile.Name);
var ext = TheFile.Extension;
var path2 = path + fname;
///As long as we got file names, same as in server..
while(new FileInfo(path2+ext).Exists)
{
///Add "-img" to its name..
path2 = path2 + "-img";
}
FileInfo ccc = new FileInfo(path2 + ext);
string f_art = ccc.Name.Replace(" ", "");///Clean space.. (Optional)
getmyfile.SaveAs(f_art);
somedb.some_photo = Path.GetFileName(f_art); ///Its not fart its file art lol!
}
else ///if file is not exist in our server..
{
var path3 = (path + Path.GetFileName(getmyfile.FileName));
FileInfo ccc = new FileInfo(path3);
string f_art = ccc.Name.Replace(" ", "");
getmyfile.SaveAs(f_art);
some.some_photo = Path.GetFileName(f_art);
}
}
}
catch(FileNotFoundException ex)
{
form.Set("lblStatus",ex.Message);
}
catch (Exception ex)
{
form.Set("lblStatus", ex.Message);
}
db.somedbs.InsertOnSubmit(somedb);
db.SubmitChanges();
return RedirectToAction("Index");
}
(Optional) Also u can use :
var f_art = System.Text.RegularExpressions.Regex.Replace(Path.GetFileNameWithoutExtension(TheFile.Name), "[^a-zA-Z]", "");
instead of using .Replace(" ",""); but at this it just cleans spaced areas and if u use the code up there its gonna clean everything except A to Z , a to z characters which means no numbers will be applied to that name nor space or other characters which are not between A and Z..

Object reference not set to an instance of an object

I keep getting the following error and I don't know how to fix it. Any help would be great please
Exception Details:NullReferenceException was unhandled by users code: Object reference not set to an instance of an object.
protected void LbUpload_Click(object sender, EventArgs e)
{
ERROR: if(FileUpload.PostedFile.FileName == string.Empty)
{
LabelMsg.Visible = true;
return;
}
else
{
string[] FileExt = FileUpload.FileName.Split('.');
string FileEx = FileExt[FileExt.Length - 1];
if (FileEx.ToLower() == "csv")
{
FileUpload.SaveAs(Server.MapPath("CSVLoad//" + FileUpload.FileName));
}
else
{
LabelMsg.Visible = true;
return;
}
}
CSVReader reader = new CSVReader(FileUpload.PostedFile.InputStream);
string[] headers = reader.GetCSVLine();
DataTable dt = new DataTable();
foreach (string strHeader in headers)
dt.Columns.Add(strHeader);
string[] data;
while ((data = reader.GetCSVLine()) != null)
dt.Rows.Add(data);
GridView1.DataSource = dt;
GridView1.DataBind();
if (FileUpload.HasFile)
try
{
FileUpload.SaveAs(Server.MapPath("confirm//") +
FileUpload.FileName);
LabelGrid.Text = "File name: " +
FileUpload.PostedFile.FileName + "<br>" +
FileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload.PostedFile.ContentType + "<br><b>Uploaded Successfully";
}
catch (Exception ex)
{
LabelGrid.Text = "ERROR: " + ex.Message.ToString();
}
else
{
LabelGrid.Text = "You have not specified a file.";
}
File.Delete(Server.MapPath("confirm//" + FileUpload.FileName));
}
You are checking if the FileName is string.Empty, it sounds like you want to detect when the user clicked the button without selecting a file.
If that happens, the actual PostedFile property will be null (remember, the user didn't posted a file), you should use the FileUpload.HasFile property for that purpose:
protected void LbUpload_Click(object sender, EventArgs e)
{
if(FileUpload.HasFile)
{
LabelMsg.Visible = true;
return;
}
// ...
}
But I would recommend you also to add a RequiredFieldValidator.
More on validation:
Validating ASP.NET Server Controls
ASP.NET Validation in Depth
Are you sure that FileUpload and FileUpload.PostedFile is not null?
Either FileUpload or its PostedFile property must be null.

Resources