I am working on an ASP.net project and I have a file upload control. I have a folder in my solution called user_uploads. How can I modify the following code in order to save the files in user_uploads when I publish the solution?
string fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs("C:\\temp\\" + fn);
you just need to do as below get the path of the folder using MapPath and than use that path to save you file ...
string path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/user_uploads");
string fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(System.IO.Path.Combine(path, fn));
//FileUpload1.PostedFile.SaveAs(path + fn);
Related
I need a library of vector files, where the same files have to be used every time. I want to load them from a folder and have the option to store new ones.
I tried having a library folder inside the WPF project that contains the files:
Solution/Project/Library/file1.dxf
I load them like this:
string currentDir = Directory.GetCurrentDirectory();
var cutOff = currentDir.LastIndexOf(#"\bin\");
var folder = currentDir.Substring(0, cutOff) + #"\Library\";
string[] filePaths = Directory.GetFiles(folder, "*.dxf");
This worked when running on the PC the project was buid, but the program crashes when the .exe is run on another PC. How do I fix this or is there a better approach to this?
Create a subfolder under Environment.SpecialFolder.ApplicationData, read the files in the library folder if it exists. If not create it and save the existing library files to it (here from resources):
string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appFolder + #"\MyAppLibrary\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
// Add existing files to that folder
var rm = Properties.Resources.ResourceManager;
var resSet = rm.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (var res in resSet)
{
var entry = ((DictionaryEntry)res);
var name = (string)entry.Key;
var file = (byte[])rm.GetObject(name);
var filePath = path + name + ".dxf";
File.WriteAllBytes(filePath, file);
}
}
// Load all files from the library folder
string[] filePaths = Directory.GetFiles(path, "*.dxf");
Thanks Jonathan Alfaro and Clemens!
Here's my code in moving excel file to be specific..
if (Directory.GetFiles(destinationPath, "*.xls").Length != 0)
{
//Move files to history folder
string[] files = Directory.GetFiles(destinationPath); //value -- D://FS//
foreach (string s in files)
{
var fName = Path.GetFileName(s); //12232015.xls
var sourcePath = Path.Combine(destinationPath, fName);
var destFile = Path.Combine(historyPath, fName); // -- D://FS//History
File.Move(fName, destFile);
}
}
But it gets an error of
Could not find file 'D:\Project\ProjectService\bin\Debug\12232015.xls'.
Why it finds under my project not on the specific folder i set?
Thank you.
You're only using the name of the file:
var fName = Path.GetFileName(s); //12232015.xls
//...
File.Move(fName, destFile);
Without a complete path, the system will look in the current working directory. Which is the directory where the application is executing.
You should use the entire path for the source file:
File.Move(sourcePath, destFile);
Explicitly specifying the full path is almost always the best approach. Relative paths are notoriously difficult to manage.
There is an Logical error. Change
File.Move(fName, destFile);
to
File.Move(sourcePath, destFile);
as fName only contains file name and not fullpath. The file is checked in working directory.
I create new folder but how to save file in that please help me.
string createfolder = "E:/tmp/jobres/" + uId;
System.IO.Directory.CreateDirectory(createfolder);
AsyncFileUpload1.SaveAs(Server.MapPath("/tmp/jobres/" + AsyncFileUpload1.PostedFile.FileName));
but how to store my file in created folder?
Since you are using MapPath on save, your directory may be created in the wrong spot. You should be using MapPath when creating your directory as well:
var createfolder = Path.Combine(Server.MapPath("/tmp/jobres/"), uId.ToString());
System.IO.Directory.CreateDirectory(createfolder);
AsyncFileUpload1.SaveAs(Path.Combine(createdFolder, AsyncFileUpload1.PostedFile.FileName));
string createfolder = "/tmp/jobres/" + uId;
System.IO.Directory.CreateDirectory(createfolder);
AsyncFileUpload1.SaveAs(Path.Combine(createfolder,AsyncFileUpload1.PostedFile.FileName));
I have a return a c# code to save a file in the server folder and to retrieve the saved file from the location. But this code is working fine in local machine. But after hosting the application in IIS, I can save the file in the desired location. But I can't retrieve the file from that location using
Process.Start
What would be the problem? I have searched in google and i came to know it may be due to access rights. But I don't know what would be exact problem and how to solve this? Any one please help me about how to solve this problem?
To Save the file:
string hfBrowsePath = fuplGridDocs.PostedFile.FileName;
if (hfBrowsePath != string.Empty)
{
string destfile = string.Empty;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\\\";
if (!Directory.Exists(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)))
Directory.CreateDirectory(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1));
FileInfo FP = new FileInfo(hfBrowsePath);
if (hfFileNameAutoGen.Value != string.Empty)
{
string[] folderfiles = Directory.GetFiles(FilePath);
foreach (string fi in folderfiles)
File.Delete(fi);
//File.Delete(FilePath + hfFileNameAutoGen.Value);
}
hfFileNameAutoGen.Value = PONumber + FP.Extension;
destfile = FilePath + hfFileNameAutoGen.Value;
//File.Copy(hfBrowsePath, destfile, true);
fuplGridDocs.PostedFile.SaveAs(destfile);
}
To retrieve the file:
String filename = lnkFileName.Text;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\";
FileInfo fileToDownload = new FileInfo(FilePath + "\\" + filename);
if (fileToDownload.Exists)
Process.Start(fileToDownload.FullName);
It looks like folder security issue. The folder in which you are storing the files, Users group must have Modify access. Basically there is user(not sure but it is IIS_WPG) under which IIS Process run, that user belongs to Users group, this user must have Modify access on the folder where you are doing read writes.
Suggestions
Use Path.Combine to create folder or file path.
You can use String.Format to create strings.
Create local variables if you have same expression repeating itself like FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)
Hope this works for you.
You may have to give permissions to the application pool that you are running. see this link http://learn.iis.net/page.aspx/624/application-pool-identities/
You can also use one of the built-in account's "LocalSystem" as application pool identity but it has some security issue's.
I m saving path of images, audio and video files that path is of folder saved at server. Now I want that path as link in c# for the purpose of download.
Is there any way how to do that?
I'm not suppose to use gridview to show link.
EDIT:-
ServerFileName = System.IO.Path.Combine(ServerSavePathI, ClientFileName);
string serverPath=Server.MapPath(ServerFileName);
FileUpload1.SaveAs(serverPath);
dbInsert("Image",fileName,fileExt,serverPath);
//dbinsert stores values to database. and in database it is showing path just as
//c:InetpubwwwRootFileUploadingpenguin.jpg and not showing
//'\\' though i have used datatype varchar
EDIT:-
protected void dbInsert(string fileType,string fileName,string fileExt,
string filePath)
{
string getSQL1;
getSQL1 = "INSERT into tbluploadedfilesdetail (FileDownloaded,FileType,
FileName,FileExt,FilePath) VALUES ('false','" + fileType + "','" +
fileName + "','" + fileExt + "','"+filePath+"');";
MySqlConnection objMyCon1 = new MySqlConnection(strProvider);
objMyCon1.Open();
MySqlCommand cmd1 = new MySqlCommand(getSQL1, objMyCon1);
cmd1.ExecuteNonQuery();
objMyCon1.Close();
dbLoad();
}
Normally if you have images in folder named images under root folder of your site and you save path for an image named image1.jpg as images/image1.jpg you can get link as follows:
var path="images/image1.jpg";//you get this from db
var link=Page.ResolveUrl("~/"+path);//gives /images/image1.jpg
~/ specified path relative to root folder of your site.
Normally I save the physical path and virtual path separately. Moreover you can get physical path from virtual path easily. You should save FileUpload/ingpenguin.jpg only and can get physical path easily as follows:
var root = Server.MapPath("/");//path to the root folder
// will return full path
var imagePath = Server.MapPath("FileUpload/inpenguin.jpg");
For more informaiton you can refer to 4guysfromrolla