i wanna create backup data in my application I used saveFileDialog, so i can place backup file anywhere i want (Dekstop, drive D, etc)
my backup file will be db, image, video so i guess it's will be easier to place that in one folder let say it's "myBackup" folder (generate automatically with C#)
so if user wanna save in Dekstop all of backup data will be in ~C:\Users\Maju\Desktop\myBackup~
i already successfully generate folder but my file won't save inside that
mySaveFileDialog.FileName = "Backup Database " + dateTimeNow;
if (mySaveFileDialog.ShowDialog() == DialogResult.OK)
{
string fileAsal = System.IO.Path.Combine(Global.myDatabaseLocation, "data.mdb");
FileInfo fi = new FileInfo(mySaveFileDialog.FileName);
string nameFolder = "myBackup";
System.IO.Directory.CreateDirectory(#fi.DirectoryName + "\\" + nameFolder);
string path = System.IO.Path.Combine (fi.DirectoryName, "\\" + nameFolder);
string pathDestination = System.IO.Path.Combine(path, mySaveFileDialog.FileName);
System.IO.File.Copy(fileAsal, pathDestination, true);
}
Is not it easier to use FolderBrowserDialog?
mySaveFileDialog.FileName already includes the path to the file so you need to write
string pathDestination = System.IO.Path.Combine(path, System.IO.Path.GetFileName(mySaveFileDialog.FileName));
Related
this code is to check does the user has upload any file and the file namd.
if (FileUpload1.HasFile) {
fileName = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Data/") + fileName);
fileLocation = Server.MapPath("~/Data/") + fileName;
}
I wonder can I add the current date on the end of the file name. my file can be any type of file. I do try add on FileName= FileUpload1.FileName+updateon; but the file will save as example.jpg11062015 and the file will be corrupted.
anyone has any idea how to do it?
You can use Path to separate FileName into a file name and an extension, insert the date in the middle, and combine them back, like this:
var fn = Path.GetFileNameWithoutExtension(FileUpload1.FileName);
var ext = Path.GetExtension(FileUpload1.FileName);
var fileName = string.Format("{0}{1:yyyy-MM-dd}.{2}", fn, DateTime.Now, ext);
Try parsing the file name into parts, and inserting your date in between, like this:
var newFileName = Path.GetFileNameWithoutExtension(FileUpload1.FileName)
+ "11062015" // or wherever the date is coming from
+ Path.GetExtension(FileUpload1.FileName);
Original file name: "someFile.ext"
Modified file name: "someFile11062015.ext"
It sounds simple but it is not. I am trying to move a file that i made it like this:
string newFileName = string.Format("{0}-{1}-{2}-t{3:00}-{4:00}.txt", 2013, 10, 5, 05, 06);
It is going to look like: 2013-10-5-05-06.txt, from the default directory (..\bin\debug\2013-10-5-05-06.txt) to another directory (c:\Users\Public\Folder). I want to keep the name of the file so that other files having almost the same name (small difference between) being moved to the same folder. I tried several methods (Path.Combine(), string.Concat()..) without success.
Just use this snippet
string CurrentFileNameAndPath; //the path the file you want to move
string newPath; //only the new the folderPath
System.IO.FileInfo FileYouWantToMove = new System.IO.FileInfo(CurrentFileNameAndPath);
string NewFileNameAndPath = newPath + "\\" + FileYouWantToMove.Name; //remember that using fullname will get the folder and filename
FileYouWantToMove.MoveTo(NewFileNameAndPath);
So lets use this as an example i have this file C:/Dir1/file1.txt and I want to change its directory to C:/Dir2/ right? then it will be like this
string CurrentFileNameAndPath = #"C:/Dir1/file1.txt";
string newPath = #"C:/Dir2/";
System.IO.FileInfo FileYouWantToMove = new System.IO.FileInfo(CurrentFileNameAndPath);
string NewFileNameAndPath = newPath + "\\" + FileYouWantToMove.Name;
FileYouWantToMove.MoveTo(NewFileNameAndPath);
the result will the that file in C:/Dir1/file1.txt will be now in C:/Dir2/file1.txt it have been moved and maintened the same file name and extension
Something like this is actually pretty trivial
var srcFile = "..\bin\debug\2013-10-5-05-06.txt";
var destFolder = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
var destFile = Path.Combine(destFolder, Path.GetFileName(srcFile));
File.Move(srcFile, destFile);
Just keep in mind that Move can throw various exceptions e.g. IOException / UnauthorizedAccessException etc. so it would be wise to handle these where appropriate.
I am using a free MS Azure virtual webserver for my site.
On my dev machine I can successfully create a CSV file, save it to a relative temp directory, and then download it to the browser client.
However, when I run it from the Azure site, I get the following error:
System.IO.DirectoryNotFoundException: Could not find a part of the
path 'D:\home\site\wwwroot\temp\somefile.csv'.
Does the free version of Azure Websites block us from saving files to disk? If not, where are we allowed to create/save files that we generate on the fly?
Code Example
private FilePathResult SaveVolunteersToCsvFile(List<Volunteer> volunteers)
{
string virtualPathToDirectory = "~/temp";
string physicalPathToDirectory = Server.MapPath(virtualPathToDirectory);
string fileName = "Volunteers.csv";
string pathToFile = Path.Combine(physicalPathToDirectory, fileName);
StringBuilder sb = new StringBuilder();
// Column Headers
sb.AppendLine("First Name,Last Name,Phone,Email,Approved,Has Background Check");
// CSV Rows
foreach (var volunteer in volunteers)
{
sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5},{6}",
volunteer.FirstName, volunteer.LastName, volunteer.MobilePhone.FormatPhoneNumber(), volunteer.EmailAddress, volunteer.IsApproved, volunteer.HasBackgroundCheckOnFile));
}
using (StreamWriter outfile = new StreamWriter(pathToFile))
{
outfile.Write(sb.ToString());
}
return File(Server.MapPath(virtualPathToDirectory + "/" + fileName), "text/csv", fileName);
}
Make sure that the ~/temp folder gets published to the server, as it's possible your publish process isn't including it.
Azure Websites provide environment variables that you can use to get to things like a temporary storage folder. For example, there is a "TEMP" variable you could access to get a path to the TEMP folder specific to your Website.
Change line 2 in your method to this:
//string physicalPathToDirectory = Server.MapPath(virtualPathToDirectory);
string physicalPathToDirectory = Environment.GetEnvironmentVariable("TEMP");
Then change the last line to this:
//return File(Server.MapPath(virtualPathToDirectory + "/" + fileName), "text/csv", fileName);
return File(pathToFile, "text/csv", fileName);
I am trying to get a path for a file which a users uploads but the path that I am getting is wrong because the path should be for an example
"C:\\Users\\Tranga.Patel\\Downloads\template.xlsx"
but on my program I get
"c:\\windows\\system32\\inetsrv\\Template Final.xlsx"
the code that I am using is
fileName = Path.GetFullPath(fileUpload.PostedFile.FileName);
I also tried using
fileName = Server.MapPath(Path.GetFullPath(fileUpload.PostedFile.FileName));
this give the directory of the project
try using following:
var path=Server.MapPath('Uploads folder path from root directory');
This gives you the folder path from the root directory of your website.
EDIT:- You should be knowing to which path users are saving the file if it is not in your site directory tree.
Are you using a File Upload control? If you are, you just need them to select the document they want to upload and then specify the path you want to save it at. For example
// Get File Name
documentName = Path.GetFileName(fuContentDocuments.FileName);
// Specify your server path
string serverPath = Server.MapPath("../../" + WebConfigurationManager.AppSettings["FilePath"].ToString());
// The final path
string fileLocation = (serverPath + "\\" + userId + "\\" + documentName);
// if folder doesn't exist then create it
if (!Directory.Exists(serverPath + "\\" + userId + "\\"))
{
// create the folder for the file
Directory.CreateDirectory(serverPath + "\\" + userId + "\\");
}
// Upload the file
fuContentDocuments.SaveAs(fileLocation);
Note: UserId is just the users login userId. This way other users wont override it.
I want to upload a file in a physical path such as E:\Project\Folders.
I got the below code by searching in the net.
//check to make sure a file is selected
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
But in that, I want to give my physical path as I mentioned above. How to do this?
Server.MapPath("~/Files") returns an absolute path based on a folder relative to your application. The leading ~/ tells ASP.Net to look at the root of your application.
To use a folder outside of the application:
//check to make sure a file is selected
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
Of course, you wouldn't hardcode the path in a production application but this should save the file using the absolute path you described.
With regards to locating the file once you have saved it (per comments):
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);
FileUpload1.SaveAs(fileName);
FileInfo fileToDownload = new FileInfo( filename );
if (fileToDownload.Exists){
Process.Start(fileToDownload.FullName);
}
else {
MessageBox("File Not Saved!");
return;
}
}
Well,
you can accomplish this by using the VirtualPathUtility
// Fileupload1 is ID of Upload file
if (Fileupload1.HasFile)
{
// Take one variable 'save' for store Destination folder path with file name
var save = Server.MapPath("~/Demo_Images/" + Fileupload1.FileName);
Fileupload1.SaveAs(save);
}