Using FileUpload C# - c#

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

Related

How to download files from OneDrive

I am looking to download my files in public folder from One Drive, but it doesn't download the files.
Here is the scenario:
In public folder I have another folder with multiple files in it and is accessible widely.
for test purpose I have shared all the files in public folder (I don't if it's proper way of sharing it).
The following links are provided for me to download the file:
From shared folder link https://onedrive.live.com/redir?resid=DBBC281099F4FE69!646&authkey=!AGRCGuw8Y2_p9mA&ithint=folder%2c.mp3
From public folder link https://onedrive.live.com/redir?resid=DBBC281099F4FE69%21646
Direct link http://1drv.ms/1z9XlW6 -
I am using BackgroundTransferRequest to download the file using below code:
string filePathToDownload = string.Empty, fileName = "111.mp3";
filePathToDownload = "http://1drv.ms/1z9XlW6";
Uri transferUri = new Uri(Uri.EscapeUriString(filePathToDownload), UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
Uri downloadUri = new Uri(DataSource.TEMPDOWNLOADLOCATION + fileName, UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = fileName;
The file is 300Kb, but this only downloads 6 Kb.
How can I directly download the file from the links above (any of them)?
thanks!
If you replace the word redir with download in the url you get the raw file instead of the webpage i.e.
https://onedrive.live.com/download?resid=DBBC281099F4FE69%21646
Basically, you can't. Those links are links to the web content that shows the files you have shared. If your scenario doesn't mind asking the user to log in to OneDrive, then you can use the Live SDK to access these files.
To access your public folder from Live SDK, you need to either use Live SDK to get the folder-id for your public folder, or convert the IDs in the URL you copied into the format the Live SDK uses:
folder.<user-id>.<folder-resid>
Where is the part of before the !. In general you shouldn't construct an ID, since it's possible the IDs will change in the future, and instead you should retrieve the ID from the service. However, with the URL you pasted the ID would be:
folder.DBBC281099F4FE69.DBBC281099F4FE69!646
Which will allow you to call
https://apis.live.net:443/v5.0/folder.DBBC281099F4FE69.DBBC281099F4FE69!646/files?access_token=<valid_token>
and retrieve the IDs for the individual files, which you can then download via Live SDK following these details: http://msdn.microsoft.com/en-US/library/dn659726.aspx#download_a_file
For those who are still looking for a response to that question.
The easiest way to find the file path is to go to One Drive on the web and right-click on the file that we want and select Embed. Ξ€hen on the right we see the info window to integrate our file into a page. Inside the iframe is the source of the file. Then we have to replace the word embed with the word download and that's it.
Try something like this
//we first need the file id
string id = string.Empty;
//we need to get all of the filenames stored in the root of the skydrive account
LiveOperationResult result = await this.client.GetAsync("me/skydrive/files");
//lets make a list of all these filenames
List<object> items = result.Result["data"] as List<object>;
//for every filename, check if it is what we want, in this case "sample.txt"
//if it is what we want, get the id and save it to out already defined id value
foreach (object item in items)
{
IDictionary<string, object> file = item as IDictionary<string, object>;
if (file["name"].ToString() == "sample.txt")
{
id = file["id"].ToString();
}
}
//to download the file we need to use the id + "/content"
LiveDownloadOperationResult result2 = await client.DownloadAsync(string.Format("{0}/content", id));
//once the file had downloaded, lets copy it to IsolatedStorage
Stream stream = result2.Stream;
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileToSave = storage.OpenFile("sample.txt", FileMode.Create, FileAccess.ReadWrite))
{
stream.CopyTo(fileToSave);
stream.Flush();
stream.Close();
}
}
here client is the object of LiveConnectClient class.
Import
using Microsoft.Live;
using Microsoft.Live.Controls;
Here is use txt file as an example. Go through this example:http://www.baileystein.com/2013/10/20/skydrive-how-to-upload-and-download-a-text-file-on-wp8/

Multiple upload files from file list in User computer to server in ASP.Net

pe someone can help me on this.
I've been googling & searching a lot regarding this issue.
I'm working on web application where I need to :
Click a button to get a folder/directory of files - Done with
javascript
Get list of available files is the selected folder/directory - Done
with javascript
Start uploading those file in the list into server folder - Failed!
As I understand my limitation so far :
I cannot programmatically assign a value to asp:FileUpload control -
readOnly
I cannot access those file in the list in FileInfo/FileStream - it's fail as it can't find the source file given from the list due to it's not
came from server directory
came from server directory
I cannot simply try to use File.Copy to upload the file - it's fail as it can't find the source file given from the list due to it's not
came from server directory
I've been getting error :
"Could not find a part of the path"
List of files in the folder, example :
File1.pdf
File2.png
File3.txt
File4.xls
File5.jpg
While in the server, I already create a folder named as "Temp" but the problem actually because system can't recognize the path of those file in the list.
This is part of my code :
string strPath = #"C:\Users\Administrator\Desktop\Sample";
string strListedFiles = txtList.InnerText.ToString();
string[] strFiles = strListedFiles.split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string strFile in strFiles)
{
FileInfo fiFile = new FileInfo(strPath.ToString() + "\\" + strFile.Trim());
FileStream fsFile = fiFile.OpenRead(); //Failed at here
...
...
...
...
}
Perhaps you are looking for something which has been shown with demo in this tutorial.
This will allow you to upload multiple files concurrently.
Another alternative example with jQuery MultiFile is given here.

Finding the exact path of the file

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'
}
}

How to open or run unknown file converted into byte[]

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.

File Upload in SilverLight?

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())
{
...
}
}

Categories

Resources