How to set physical path to upload a file in Asp.Net? - c#

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);
}

Related

File.Copy error - C# - IOException The filename, directory name, or volume label

Trying to copy all files/directories inside a directory to a new location that I create.
Users select the 'backup drive' to work with to in a combobox, then when they click the backup desktop button it simply creates a backup directory on that drive and copies all the files into that directory.
The backup directory gets created on the drive appropriately - but the first file it hits it kicks off an error.
private void backupDesktopButton_Click(object sender, EventArgs e)
{
//set the destionationLocation to the selectedDrive
string selectedDrive = backupDriveCombo.SelectedItem.ToString();
string destinationLocation = selectedDrive+"Backups-" + DateTime.Now.Month.ToString()+"-"+DateTime.Now.Year.ToString()+"\\Desktop\\";
if (!Directory.Exists(destinationLocation))
{
Directory.CreateDirectory(destinationLocation);
}
string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string[] fileList = Directory.GetFiles(desktopFolder);
foreach (string file in fileList)
{
//move the file
File.Copy(file, destinationLocation);
}
}
I get the error:
IOException was unhandled.
The filename, directory name, or volume label syntax is incorrect.
In the 'Autos' window (VS2010) I see the locations are set correctly:
destinationLocation = the appropriate directory (C:\Backups-8-2016\Desktop\)
file = the appropriate first file (C:\Users\myusername\Desktop\myshortcut.url)
What am I missing? I have all rights to be able to copy/paste/create things and the directory to store it gets created - just a problem moving the file.
From the documentation https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx
the second parameter:
The name of the destination file. This cannot be a directory or an existing file.
you need to concat the filename to the folder.
Try something like this
string[] fileList = Directory.GetFiles(desktopFolder);
foreach (string file in fileList)
{
string targetFile = Path.Combine(destinationLocation, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile);
File.Copy(file, targetFile);
}

Saving images to a project folder in asp.net/c#

In my method, I'm trying to save an image in a folder in the directory of my project. I have tried just putting the direct filepath of the folder, but that gives me an error when the project runs.
Is there a built-in extension of some kind in c# that would allow me to save this image in a folder in my directory; or way to simply access my directory without drilling to where my project is saved on my computer?
private void CreateBarcode()
{
var bitmapImage = new Bitmap(500,300);
var g = Graphics.FromImage(bitmapImage);
g.Clear(Color.White);
UPCbarcode barcode = new UPCbarcode(UPCbarcode.RandomGeneratedNumber(), bitmapImage, g);
string filepath=#"images/image1.jpg";
bitmapImage.Save(filepath,System.Drawing.Imaging.ImageFormat.Jpeg);
}
You can always use the AppData folder,
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Assuming the "Image" folder is in the root directory of your Project use:
Server.MapPath("~/Image" + filename)
you can check if the file already exist at a location by :
if (!File.Exists(filePath))
{
// Your code to save the file
}
I can guess that there is similarity in the name of the image file
try putting it under a different name
like
string filepath = # "images / blabla or AI.jpg";
Use this
string filepath= Application.StartupPath + "\images\image1.jpg";
bitmapImage.Save(filepath,System.Drawing.Imaging.ImageFormat.Jpeg);

How to get path of file from which folder it is browse in ASPxUploadControl?

I want to get file path of uploaded file. I have excel file in folder and in excel file I have files name which is also in same folder. I am trying to upload only excel file. It uploaded successfully but cannot get uploaded file path. On the base of file path I have to get all the files whose name are in excel file. I am trying this code... Please help me in this regard.
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
String strFilename = e.UploadedFile.FileName;
String strPath = Path.GetFullPath(e.UploadedFile.FileName);
DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(strPath);
}
An ASPxUpload control will save to App_Data/UploadTemp and then you decide where the file is saved to when you do this:
e.UploadedFile.SaveAs(m_fullpath, true); //true means overwrite
The uploaded file can be used to get .xls files by doing this:
string m_filename = e.UploadedFile.FileName;
string m_extension = Path.GetExtension(m_filename);
So you can do something like...
if(m_extension == ".xls")
{
e.UploadedFile.SaveAs(m_fullpath, true);
}
The better approach is to set the file types that are allowed in the upload control.
<ValidationSettings AllowedFileExtensions=".xls, .xlsx"></ValidationSettings>

How to rename File in FileUpload Control Asp.net?

I've Method that carry the uploaded Image and I need to rename it to have Fixed Name in my application But when using File.Copy Method it returns result with (File not Exist)
I don't Know how is that
I tried This File.Copy (UploadFile.FileName, newFilName);
also not responding
string filename = Path.GetFileName(FileUpload.FileName);
string extension = Path.GetExtension(FileUpload.PostedFile.FileName);
string oldFileName = FileUpload.FileName;
string newFileName = ("aboutusImage" + extension);
File.Copy(oldFileName, newFileName);
File.Delete(oldFileName);
File.Move(FileUpload.FileName, newFileName);
FileUpload.SaveAs(Server.MapPath("~/Styles/aboutusImages/") + newFileName);
var updateAboutus = (from a in dbContext.DynamicText
where a.Id == 1
select a).Single();
updateAboutus.Id = updateAboutus.Id;
updateAboutus.Name = updateAboutus.Name;
updateAboutus.Image = Path.Combine("~/Styles/aboutusImages/", "aboutusImage.jpg");
dbContext.SaveChanges();
FileUpload.FileName property represents the file name on the client machine, not on your server.
Trying to File.Copy on it have very few possibility to succeed unless you have the same file in your own server in the current folder.
From the MSDN example
protected void UploadButton_Click(object sender, EventArgs e)
{
// Specify the path on the server to
// save the uploaded file to.
String savePath = #"c:\temp\uploads\";
// Before attempting to perform operations
// on the file, verify that the FileUpload
// control contains a file.
if (FileUpload1.HasFile)
{
String fileName = FileUpload1.FileName;
// Append the name of the file to upload to the path.
savePath += fileName;
// Call the SaveAs method to save the
// uploaded file to the specified path.
// This example does not perform all
// the necessary error checking.
// If a file with the same name
// already exists in the specified path,
// the uploaded file overwrites it.
FileUpload1.SaveAs(savePath);
Of course, the following File.Delete, File.Move have the same problem and should be removed
The name you are trying to move from is just the name that was given on the client side, not the current name on the server. It is probably on some temporary location on the server.
You probably want the FileUpload.SaveAs function.

C# mass File renamer

i want to create C# mass file renamer, here is my UI
i have created tes folder, inside of tes there's a file which is 1.txt.
i want to create my program to add prefix and suffix to the files, so 1.txt will become
prefix1suffix
but then i got an error
it's said file already exist though there's only one file on tes folder, which is 1.txt how do i make it work ? where's the error comes from ?
i have tried the following code
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
File.Move(f.FullName,"stackoverflow");
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
and it returns same error as the second picture above.
the following picture is tes folder, there's nothing in tes folder except 1.txt
You are calling File.Move() with a full path for your sourceFileName and a relative path for your destFileName. The relative file path is relative to the current working directory and not to the source file path. I expect that a stackoverflow file exists in the current working directory, most likely created the first time you ran this code.
your File.Move is changing them all to StackOverflow not using the prefix and suffix. If you only have one file in the directory it shouldn't be an issue. Are you sure there is only 1 file?
public static void Move(
string sourceFileName,
string destFileName
)
Looking at this answer might be the clue as you are specifying relative path for the destination file. To obtain the current working directory, see GetCurrentDirectory
The sourceFileName and destFileName arguments are permitted to specify
relative or absolute path information. Relative path information is
interpreted as relative to the current working directory.
You should change
File.Move(f.FullName,"stackoverflow");
to
string fileName = f.Name.Replace(f.Extenstion,string.Empty);
string newFileName = string.Format("{0}{1}{2}",prefix,fileName,suffix);
string newFileWithPath = Path.Combine(f.Directory,newFileName);
if (!File.Exists(newFileWithPath))
{
File.Move(f.FullName,newFileWithPath);
}
The code above will give you that error since, after the first run through, "stackoverflow" exists as a file. Make sure that you check if the destination file exists (using File.Exists) before calling File.Move.
Since your goal is renaming, I would suggest using a test folder filled with files rather than using a piecemeal approach. See if something like this helps:
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
f.MoveTo(#filepath + #"\" + prefix + f.Name.Insert(f.Name.LastIndexOf('.'),suffix));
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
on a side note using a listview to display the filenames and the changes before they're committed will help prevent unwanted changes.

Categories

Resources