HI
I Try Upload a file in Silver-Light. for doing this I use System.IO.File to read file bytes and then send the data to service to insert that data as file data in Database.
(Blow Code)
byte[] data;
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Excel Files (*.xlsx)|*.xlsx";
if (open.ShowDialog()==true)
{
open.File.OpenRead();
data=System.IO.File.ReadAllBytes(open.File.FullName);
//---- send for service ---Service.savefileindatabase(data);
}
so when use this code in line which include "ReadAllBytes" exception throw by VS, this is Exception Detail:
"File operation not permitted. Access to path '' is denied."
(for more info that file which i selected was in local Drive)
So What do I do?
In Silverlight there are far more restrictions than in usual wpf programming. The files you might upload may be only in specific directories and some methods are not available like File.FullName. Only a manually selected file might be uploaded. Your starting code is OK. But in silverlight you do not have access to paths (only to the name).
There are some OpenText, OpenRead methods which allow you to get a stream from the selected file. From that point you'll be able to do what you want with the data coming from the stream.
if (open.ShowDialog())
{
using (StreamReader reader = open.SelectedFile.OpenRead())
{
...
}
}
Related
I have the following method that validates if certain file exist in the a zipped file.
The method might get a zipped file or not from IFormFile.
private static bool FileExistsInZip(IFormFile uploadedFile, string fileName)
{
using ZipArchive archive = new ZipArchive(uploadedFile.OpenReadStream(), ZipArchiveMode.Read);
return archive.Entries.Any(entry => entry.Name.Equals(fileName, StringComparison.OrdinalIgnoreCase));
}
So in the above method, uploaded file could be zip file or just text file or an image. I was wondering if ZipArchive will return false in this case but it throws ArgumentOutOfRange exception when trying to open file type that is not in Zip format. For example a 4 byte txt file.
What would be the right approach to handle this kind of scenario ?
The typical solution when there is an exception is to catch it and handle it somehow.
However, if you want to test if a file is a zip file you can instead check the header. For zip files this should be 0x04034b50. So something like:
using var br = new BinaryReader(uploadedFile.OpenReadStream());
if(br.ReadUint32 == 0x04034b50){
//is zip file
}
This will only check if the header has the correct magic numbers, it will not tell if the actual file is corrupted, for that you might need to read the entire file, including any entries, and catch any exception that occur. If you want to know the specific file type there are lists of magic numbers for different file formats.
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));
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'
}
}
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.