Not getting the Uploaded filepath in asp.net - c#

I want to save file to a specific location with some folder creation based on my requirement. So I wrote the below code.
public string CreateFilePath(string addedFolderName)
{
string folderPath = ConfigurationManager.AppSettings["DocDirectory"].ToString();
string FileUplPath = folderPath + "\\" + addedFolderName + "\\";
if (!Directory.Exists(FileUplPath))
{
Directory.CreateDirectory(FileUplPath);
}
flUploadDocs.SaveAs(FileUplPath + Path.GetFileName(flUploadDocs.FileName));
return folderPath;
}
But I am unable to get the filepath here. I am getting it as null
getting null at
Path.GetFileName(flUploadDocs.FileName)
<asp:FileUpload ID="flUploadDocs" runat="server" />
Please suggest what is wrong here.

Path.GetFileName() returns the file name and extension of the specified path string
if im correct this only fills in the file name and not the directory + name.
Path.GetFileName(flUploadDocs.FileName)
possible solution
Path.GetFileName(FileUplPath+flUploadDocs.FileName)
eventough im confused why you try to retrieve the path again after just having saved it?

The issue is that the webservice does not have the fileupload data. Here is the full code from our extended conversation:
[WebMethod]
public static string InsertUpdateMWSiteData(MWInsertUpdateFields MWInsertUpdateFields)
{
string strInsertUpdateMWInfo = "";
try
{
Dashboard dshb = new Dashboard();
dshb.CreateFilePath(MWInsertUpdateFields.SapID + "_" + MWInsertUpdateFields.CandidateID);
strInsertUpdateMWInfo = CommonDB.InsertUpdateMWSiteInfo(MWInsertUpdateFields);
}
catch (Exception)
{
throw;
}
return strInsertUpdateMWInfo;
}
public string CreateFilePath(string addedFolderName)
{
string folderPath = ConfigurationManager.AppSettings["DocDirectory"].ToString();
string FileUplPath = folderPath + "\\" + addedFolderName + "\\";
if (!Directory.Exists(FileUplPath))
{
Directory.CreateDirectory(FileUplPath);
}
if (flUploadDoc.HasFile == true)
{
string strFilename = Path.GetFileName(flUploadDoc.FileName);
flUploadDoc.SaveAs(FileUplPath + Path.GetFileName(flUploadDoc.PostedFile.FileName));
}
return folderPath;
}
The problem is that after uploading a file, a request is sent to a webmethod which is being hosted in another instance of the program. This Webmethod checks its own instance for the fileupload control and data, and doesn't find it because it is in a different instance. This is why your fileupload control is returning null even on a sanity check of .HasFile().
One solution is to pass the data to the Webservice. You could for example pass the data to your webmethod as a byte[], and then on the webservice side reconvert it back into its original file type. After completing this process, save the file to your local filesystem. To do this you may need to pass the extension type and file name.
You may also want to add some validation to limit the file types accepted to only the most common file types like images, .doc, .excel, and whatever you have the library to support the conversion of.
If you want to save files directly to your filesystem using the upload control, you can do so but you will have to exclude the webservice step.
Please also see the discussion in chat for details.

Related

Store locally a binary file file received as HTTP POST body [duplicate]

I want upload an image file to project's folder but I have an error in my catch:
Could not find a part of the path 'C:\project\uploads\logotipos\11111\'.
What am I do wrong? I want save that image uploaded by my client in that folder... that folder exists... ah if I put a breakpoint for folder_exists3 that shows me a true value!
My code is:
try
{
var fileName = dados.cod_cliente;
bool folder_exists = Directory.Exists(Server.MapPath("~/uploads"));
if(!folder_exists)
Directory.CreateDirectory(Server.MapPath("~/uploads"));
bool folder_exists2 = Directory.Exists(Server.MapPath("~/uploads/logo"));
if(!folder_exists2)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo"));
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/"));
}
catch(Exception e)
{
}
Someone knows what I'm do wrong?
Thank you :)
Try this:
string targetFolder = HttpContext.Current.Server.MapPath("~/uploads/logo");
string targetPath = Path.Combine(targetFolder, yourFileName);
file.SaveAs(targetPath);
Your error is the following:
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
You check if a directory exists, but you should check if the file exists:
File.Exists(....);
You need filename
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/" + your_image_fillename));
Remove the last part of the path to save you have an extra "/"
It should be
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName);
Also you do not have a file extension set.

Add date stamp on uploaded file

I'm currently developing a website using asp and c#. One of the pages allows registered users to upload files. These files get stored according to the user who is logged in. A directory is created when they hit upload with there login name and id.
string userDirectory = "\\Test\\Files\\ " + User.Identity.Name + " " + User.Identity.GetUserId();
if (!Directory.Exists(userDirectory))
{
Directory.CreateDirectory(userDirectory);
}
The directory gets created without an issue and file also gets uploaded. However the problem I am now facing is I'm trying to add a date stamp to a file if it already exist in the directory so I don't overwrite it. See the code below
string fileName = Path.Combine(userDirectory, FileUpload1.FileName);
if (!File.Exists(fileName))
{
FileUpload1.SaveAs(fileName);
}
else
{
fileName = string.Concat(
Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString("_yyyy_MM_dd_HH:mm:ss"),
Path.GetExtension(fileName)
);
FileUpload1.SaveAs(fileName);
}
This keeps giving me an error:
System.Web.HttpException: The SaveAs method is configured to require a rooted path, and the path 'Test.docx' is not rooted
Does anyone know where I'm going wrong? Thanks in advance
You have to append the directory name to the path, since you stripped it off (by using GetFileNameWithoutExtension):
string newFileName =
Path.Combine( Path.GetDirectoryName(fileName)
, string.Concat( Path.GetFileNameWithoutExtension(fileName)
, DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss")
, Path.GetExtension(fileName)
)
);
Also note that using : in a file name is not supported, so I replace it with _.

How to check a folder exists in DropBox using DropNet

I'm programming an app that interact with dropbox by use DropNet API. I want to check if the folder is exist or not on dropbox in order to I will create one and upload file on it after that. Everything seen fine but if my folder is exist it throw exception. Like this:
if (isAccessToken)
{
byte[] bytes = File.ReadAllBytes(fileName);
try
{
string dropboxFolder = "/Public/DropboxManagement/Logs" + folder;
// I want to check if the dropboxFolder is exist here
_client.CreateFolder(dropboxFolder);
var upload = _client.UploadFile(dropboxFolder, fileName, bytes);
}
catch (DropNet.Exceptions.DropboxException ex) {
MessageBox.Show(ex.Response.Content);
}
}
I'm not familiar with dropnet, but looking at the source code, it appears you should be able to do this by using the GetMetaData() method off of your _client object. This method returns a MetaData object.
Example:
//gets contents at requested path
var metaData = _client.GetMetaData("/Public/DropboxManagement/Logs");
//without knowing how this API works, Path may be a full path and therefore need to check for "/Public/DropboxManagement/Logs" + folder
if (metaData.Contents.Any(c => c.Is_Dir && c.Path == folder)
{
//folder exists
}

how to avoid image getting loaded from the cache

I am using asp.net file upload control
I am uploading the image to the server as as UserID+"ProfilePic" .
After uploading I am setting an image src to this via code behind
string FolderPath = System.Configuration.ConfigurationManager.AppSettings["PATH"].ToString();
string assoid = HttpContext.Current.Session["strAssociateId"].ToString()+"ProfilePic.jpg";
if (FileUpload1.HasFile)
{
try
{
string fileName = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(FolderPath +assoid);
string imagePath = "serverpath" +assoid;
face_crop_original.Src = imagePath; //Problem is here
}
}
So here what happens is the image is getting uploaded, but when I set the image.Src=xxxx it's taking the old image from cache!! Please help.
public static string VersionCssUrl(string url)
{
// Get physical path.
try
{
var path = HttpContext.Current.Server.MapPath(url);
return url + "?v=" + String.Format(File.GetLastWriteTime(path).ToString("MMddyyhhmmss"));
}
catch
{
return url;
}
}
and your code will look like this
<img src="<%= VersionCssUrl("your src".ToString()) %>" />
Now,Explaination you know what will happen is this will request the file everytime but it will check modification date of your file so you will have previous one if does not changed will definately load from cache.....
and if your file has been changed it will load new file automatically this all depends on your datetime.....
i hope this will help you regards...:)
I found a simple solution which is working for me :)
You can check the source here
What I did is I attached the datetime.now as #dholakiyaankit suggested but in a different place
string fileName = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(FolderPath +assoid);
string imagePath = "server path" +assoid;
face_crop_original.Src = imagePath+"?"+DateTime.Now;
NOTE: Here my imagepath variable will be "xxxxxx.jpg" so
face_crop_original.Src = imagePath+"?"+DateTime.Now;
will be "http://xxxxxxxx.com/imagename.jpg?Randomnumber"
This enabled me to upload the image with same name (USERID+"Profilepic") and i need not write code for deleting older file as the name will be same and it will be replaced in server !

File.Exists(file) is false but file exist

I'm add a file in one controller and in another controller I want check if the file is exist. I' using File.Exist(file), but it's always false, even if the file exist...
I adding file, and image is added successful.
if ((image!= null & image.ContentLength > 0))
{
string name = event.EventId.ToString() + ".jpg";
var fileName = name;
var path = Path.Combine(Server.MapPath("~/App_Data/Plakaty"), fileName);
plakat.SaveAs(path);
}
I'm checking in another controller if this file exist:
string file = "~/App_Data/Plakaty/" + wyd.EventId.ToString() + ".jpg";
ViewBag.file_exist = System.IO.File.Exists(file); //always is false
And my View: (It's returning only "No file")
#if (ViewBag.file_exist == true)
{
<p>File exist</p>
}
else
{
<p>No file</p>
}
You need to do the Server.MapPath again when checking the file and do the forward slash.
string file = Server.MapPath("~") + #"\App_Data\Plakaty\"
+ wyd.EventId.ToString() + ".jpg";
ViewBag.file_exist = System.IO.File.Exists(file ); //always is false
You forgot to write Server.MapPath when checking if file exist
Have you checked permissions?
The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file. See documentation
However most likely is what #Obama answered about the path being wrong as you didn't call Server.MapPath

Categories