I am using the fileUpload control. When I upload the file, I want to find the exact location of the file.
I tried using:
string fname= Server.MapPath(FileUpload2.FileName);
string fname= FileUpload2.FileName;
string fname= FileUpload2.PostedFile.FileName;
Numbers 2 & 3 gave me the name of the file. Number 1 gave me the the path of my website location. I do not know what is the difference between 2 and 3, why both gave me same results.
I read somewhere, that you cannot get the path. Is it true? If not, what code should I use?
There is no actual file path because a file uploaded to the server is simply held in memory.
The FileUpload control is just a wrapper around an HttpPostedFile instance, which itself is basically just a wrapper around an InputStream.
It's up to you to actually save the file somewhere. Until then it doesn't exist in any physical location.
The FileName property simply corresponds to the filename from the client's machine, minus the path. It has no correlation to anything on the server's file system.
There are a couple of different ways you can deal with the file.
Save The File To Disk:
The FileUpload control provides a SaveAs method that will allow you to save the file locally, or some UNC that you have access to.
FileUpload2.SaveAs("C:\\Temp\\" + FileUpload2.FileName);
Process The File In Memory:
Since you have access to the FileContent, you could simply manipulate and process the file directly. Assuming you know what type of file it is (txt, pdf, csv, etc...)
using (var sr = new StreamReader(FileUpload2.FileContent))
{
while ((var line = sr.ReadLine()) != null)
{
//Do something with 'line'
}
}
Related
I'm using C# windows application .
I want to save files in my local system.
I used Open File dialog to attach the files.
Here the text inside the file is copying,I want the file itself to get copied with a new name.But what I am really looking for is , it should just save the file automatically and not show the SaveDialog Box?
How it can be done in windows application.Can anybody help me please?
The code is shown below:
private string GetFileName()
{
OpenFileDialog op1 = new OpenFileDialog();
DialogResult result = op1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
txtEn.Text = op1.FileName;
FileName = op1.FileName;
//MessageBox.Show(FileName);
File.Copy(op1.FileName, #"D:\Backup\");
}
return FileName;
}
SQL Server 2012 seems unrelated to your question. Provided that you have proper access rights to the target directory, then in order to automate the procedure (as per your question) you don't need to use the OpenFileDialog; just a single line should suffice the goal:
//Overwriting a file of the same name is not allowed
File.Copy(FileName, #"D:\Backup\" + FileName)
or
//Overwriting a file of the same name is allowed
File.Copy(FileName, #"D:\Backup\" + FileName, true)
You can also apply some additional logic pertinent to backup file naming (upon necessity).
Hope this may help. Best regards,
Are you trying to copy a file from some x location on your file system to y location (in your case D:\Backup folder) in the file system? If that is the requirement here, I see that you are using the FileName property of OpenFileDialog which gets the File path. This you are appending to D:\Backup. You should instead use the Path.GetFileName property to first extract the file name with extension and then append it to the new folder path
File.Copy(fileName, #"D:\Backup\" + Path.GetFileName(fileName));
ok, i found this on internet to upload some files.
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);
}
and this
//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);
}
what is the difference, which one to use? i got confuse. by the way, if i can store file path in database, and next time when i want to delete or see that file, how can i retrieve that? so let say, first i add a record to database and uploaded a .doc file / excel file, next time when i want to edit that record, i want to retrieve the uploaded file, and show it in UI. thanks.
use second one cause it will convert relative or virtual path to real path itself . .u should get path from db and use it to resolve the path the same way you are storing and do manipulation on it delete and etc. for displaying url="~/Files/yourfilename"
yourfilefromdb -u retrieve it from db
string filepath = Path.Combine(Server.MapPath("~/Files"), yourfilefromdb);
File.Delete(filepath);
for showing
if it accessible directly u can just write url="~/Files/yourfilefromdb"
The only difference in two code blocks posted you is in specifying file path.
In case 1, static location is specified to save the file. It can cause problem, if location to save files differ in your production environment. It will require rebuild in that case.
While, in case 2, location is specified using relative path. So, it will always save files at "/Files" location.
//if you already know your folder is: E:\ABC\A then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/ABC/A and you want to know the real path in the disk...
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);// they know the right path so .they using directly
FileUpload1.SaveAs(fileName);
}
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);// i don't know path is correct or not so they using Server.MapPath. . .
FileUpload1.SaveAs(fileName);
}
I have code that reads encrypted credentials from a text file. I updated that text file to include a connection string. Everything else is read and decrypted fine, but not the connection string (naturally, I updated my code accordingly, too).
So I got to wondering: is it reading the correct file. The answer: No! The file in \bin\debug is dated 6/5/2012 9:41 am, but this code:
using (StreamReader reader = File.OpenText("Credentials.txt")) {
string line = null;
MessageBox.Show(File.GetCreationTime("Credentials.txt").ToString());
...shows 6/4/2012 2:00:44 pm
So I searched my hard drive for all instances of "Credentials.txt" to see where it was reading the file from. It only found one instance, the one with today's date in \bin\debug.
???
Note: Credentials.txt is not a part of my solution; should it be? (IOW, I simply copied it into \bin\debug, I didn't perform an "Add | Existing Item")
Provided you don't change the current directory, the file in bin\Debug is going to be the one being read, as you're not specifying a full path.
The problem is likely due to the differences between the different File dates. The Creation Date (which is what you are fetching and displaying as 6/4 # 2:00:44pm) is likely different from the Date modified (which is what is shown by default in Windows Explorer). This date can be fetched using File.GetLastWriteTime instead of GetCreationTime.
That being said, I would recommend using the full path to the file, and not assuming that the current directory is the same as the executable path. Specifying the full path (which can be determined based on the executable path) will be safer, and less likely to cause problems later. This can be done via:
var exePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
var file = System.IO.Path.Combine(exePath, "Credentials.txt");
using (StreamReader reader = File.OpenText(file)) { // ...
I have a project where I get a list of file location strings that I want to save locally. I want to use a FileUploader to do so. I am trying something like this so far:
FileUpload filesaver = new FileUpload();
//Iterate over each files (InputFiles is a linked list of file locations)
foreach (string File in InputFiles)
{
//Get file
Stream fileLoaded = OpenFile(File);
filesaver.FileContent = fileLoaded;
//Save file
filesaver.SaveAs(DownloadLocation);
//Code...}
The problem is that filesaver.FileContent = fileLoaded; is not a valid call (FileContent is read only).
How would I be able to get the file to the file loader so that I can save it if I have a string of that file location?
Edit I am using the FileUpload Class
The ASP.NET FileUploader has the client side send the file to the server side. It does not send a file path as a string, so there is no way to intercept the file path and "upload" on the server side. if that is your intent, you are not going to find a way to get there from here.
If you want to save the actual file binary bits once it gets to the server, there are plenty of examples out there that persist the data to databases or file system.
If you are trying to get paths as strings, the file uploader is not your best choice, but note that the file path strings, if they are local to the client, are of no use on the server side.
You can just use:
If (filesaver.HasFile)
{
filesaver.SaveAs("C:\YourFilePath\" & filesaver.FileName);
}
I use to store document/file in byte[] in database, and I want user can view/run that file from my application.
You need to know the file extension for the file you're writing, so the OS can run the default program based on the extension. The code would be something like this:
byte[] bytes = GetYourBytesFromDataBase();
string extension = GetYourFileExtension(); //.doc for example
string path = Path.GetTempFileName() + extension;
try
{
using(BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create)))
{
writer.Write(yourBytes);
}
// open it with default application based in the
// file extension
Process p = System.Diagnostics.Process.Start(path);
p.Wait();
}
finally
{
//clean the tmp file
File.Delete(path);
}
You will need to store the file extension in the database too. If you don't have the file extension the problem becomes very difficult as you cannot rely on the operating system to work out which program to launch to handle the file.
You can use the following pattern:
Load data from database and save to file using the original file extension.
Start a new System.Diagnostics.Process that points to the saved file path.
As you have saved the file with the original file extension, the OS will look for a program that is registered for the extension to open the file.
As chibacity and Daniel suggest, storing the file extension in the db, and agreed -- storing the file extension, or at least some indicator that tells you the file type, is a good idea.
If these files are of a format of your own creation then you might also want to store information about which version of the file format the data is stored in. During development file formats are prone to changing, and if you don't remember which version you used to store the data then you have a hard job recovering the information.
The same problems are faced in object persistence generally.