I am using the following code to upload a file and save it on the disk. The filename is like:
BodyPart4353453453
E.g. When I upload a file called alfa.txt it will be saved as BodyPart24245343.
How can I set the filename each time?
var uploadFolder = "/Content/Images/" + listingId;
var provider = GetMultipartProvider(uploadFolder);
var result = await Request.Content.ReadAsMultipartAsync(provider);
Try somthing like this.
// change file name with its extension
var fileName = Guid.NewGuid().ToString() +
System.IO.Path.GetExtension(file.FileName);
var uploadUrl = Server.MapPath("~/uploads");
file.SaveAs(Path.Combine(uploadUrl, fileName));
Related
using Ionic.Zip;
var savedzipFile = "C:\alldocs\issues\issuesfromtoday.zip";
var selectedfolderfromDialog = "D:\MyDocs";
This is what I have. I cant use webblient because its not a url. How to I save the zip file to that selected folder location? Zip file has PDFs if that matters.
This should do the trick:
var savedzipFile = #"C:\alldocs\issues\issuesfromtoday.zip";
var selectedfolderfromDialog = #"D:\MyDocs";
using (var sourceStream = System.IO.File.Open(savedzipFile, System.IO.FileMode.Open))
{
using (var targetStream = System.IO.File.OpenWrite(selectedfolderfromDialog + #"\" + savedzipFile.Substring(savedzipFile.LastIndexOf('\\'))))
{
sourceStream.CopyTo(targetStream);
}
}
When i click the download link it send me to a error page trying to debug it its telling me that my given paths format is not supported
In my controller class:
public async Task<ActionResult> DownloadBlob(string file, string extension)
{
string downloadPath = await repo.DownloadBlobAsync(file, extension);
return Json(downloadPath);
}
In My Blob Storage class:
public async Task<string> DownloadBlobAsync (string file, string fileExtension)
{
_cloudBlobContainerx = _cloudBlobClientx.GetContainerReference(containerNamex);
CloudBlockBlob blockBlob = _cloudBlobContainerx.GetBlockBlobReference(file + "." + fileExtension);
var path = downloadPath + file + "." + fileExtension;
using (var fileStream = System.IO.File.OpenWrite(path))
{
fileStream.Position = 1;
//fileStream.Seek(0, SeekOrigin.Begin);
await blockBlob.DownloadToStreamAsync(fileStream);
return path;
}
}
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NotSupportedException: The given path's format is not supported
The source of the error :
using (var fileStream = System.IO.File.OpenWrite(path))
According to your description, I suggest you could set a break point to check the value of downloadPath or 'path' field.
I have created a simple demo to download a blob file to a local folder path. It works fine. You could refer to.
string containerNamex = "container002";
string file = "MyTest"; //a blob file named MyTest.txt
string fileExtension = "txt";
string downloadPath = #"D:\MyBlob\";
CloudBlobClient _cloudBlobClientx = storageAccount.CreateCloudBlobClient();
_cloudBlobContainerx = _cloudBlobClientx.GetContainerReference(containerNamex);
CloudBlockBlob blockBlob = _cloudBlobContainerx.GetBlockBlobReference(file + "." + fileExtension);
var path = downloadPath + file + "." + fileExtension;
using (var fileStream = System.IO.File.OpenWrite(path))
{
fileStream.Position = 1;
blockBlob.DownloadToStreamAsync(fileStream);
Console.WriteLine("success");
}
The result like this:
I need to store a byte[] in memory. I need to access it later. The byte[] represents a video. The following code will allow the file to be written to memory, as well as accessed from memory. When the remove method shown below is called, it can still be accessed later.
I have checked that the pathname is the same.
public void StoreVideo(byte[] video, string filename)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directoryname = Path.Combine(documents, "Videos");
Directory.CreateDirectory(directoryname);
var path = Path.Combine(directoryname, filename);
File.WriteAllBytes(path, video);
}
public void RemoveVideo(string filename)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directoryname = Path.Combine(documents, "Videos");
var path = Path.Combine(directoryname, filename);
File.Delete(filename);
}
public byte[] GetVideo(string filename)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directoryname = Path.Combine(documents, "Videos");
var path = Path.Combine(directoryname, filename);
if(File.Exists(path))
{
return File.ReadAllBytes(path);
}
return null;
}
The answer to this was just a small brain fart on the path being passed to the File.Delete method. However for those who run into this you should be aware that File.Delete DOES NOT throw any exception if it cannot delete the file. It should be good practice to wrap the File.Delete method a check for File.Exists
I have my Info.plist file setup to handle the file type I want. When I download the file in Safari, and pick my App from the Open In, the file does get sent to my app and the OpenUrl function is called. In the Simulator, I am able to open the file using FileStream and process it without any problem. On the real device, I get an error that says something like:
Accesss to the path "/private/var/mobile/Containers/Data/Application/{KEY}/Documents/Inbox/file.ext is denied.
Here is my OpenUrl function:
public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
try
{
System.Console.WriteLine("OpenURL");
var fileName = url.AbsoluteUrl.LastPathComponent;
var newPath = Path.Combine(bookStorage, fileName);
var input = new System.IO.FileStream(url.Path, FileMode.Open);
var output = new System.IO.FileStream(newPath, FileMode.Create);
input.CopyTo(output);
output.Close();
input.Close();
var epub = new EpubParser(bookStorage, fileName);
var publication = new Publication(epub.getTitle(), fileName);
var id = epub.getId();
if (id != null)
{
publication.Id = id;
}
publication.Picture = epub.getImage();
var publications = new Publications();
publications.AddPublication(publication);
return true;
}
catch (Exception e)
{
var navController = (UINavigationController)this.Window.RootViewController;
var controller = navController.ViewControllers[0];
AlertView.Show(e.Message, controller);
return false;
}
}
Basically all I wanted was to copy the file to another location to keep it stored. So I used File.Copy instead and it worked! Apparently FileStream even with just the Open permissions set, still requires some type of write access to the folder.
var fileName = url.AbsoluteUrl.LastPathComponent;
var newPath = Path.Combine(bookStorage, fileName);
File.Copy(url.Path, newPath);
I am using Response.TransmitFile() to download a zip folder from a folder on my C drive. The folder downloads fine and i get the files turn up in my downloads folder. However the problem is in my downloads folder, with a zip file that has the name of the asp page, and inside is the folder that i wanted to download. The other problem is i append a DataTime on the end of the zip folder in the upload, but the date is not on the end of the folder name either.
My Upload Code looks like this:
string pnq = HttpContext.Current.Request.Url.PathAndQuery;
string url = HttpContext.Current.Request.Url.AbsoluteUri.Replace(pnq, "/");
if (FileUpload1.HasFile)
{
var filename = FileUpload1.PostedFile.FileName;
var uriID = Guid.NewGuid().ToString();
var password = System.Web.Security.Membership.GeneratePassword(7, 2);
filename = filename.Remove(filename.Count() - 4) + "-" + DateTime.Now.ToShortDateString() + ".zip";
filename = filename.Replace(" ", "-");
filename = filename.Replace("/", "-");
FileUpload1.SaveAs("C:\\Uploads\\" + filename);
lblUri.Text = url + "UICDownload.aspx?fileID=" + uriID;
lblPassword.Text = password;
string file = MapPath("~/Sample.xml");
XDocument doc = XDocument.Load(file);
doc.Root.Add(new XElement("File", new XElement("name", filename), new XElement("uriID", uriID), new XElement("password", password)));
XElement name = new XElement("name", filename);
doc.Save(file);
}
My Download Code looks like this:
var text = Request.QueryString["fileID"];
string file = MapPath("~/Sample.xml");
XDocument doc = XDocument.Load(file);
var node = doc.Document.Descendants("uriID").FirstOrDefault(u => u.Value.Equals(text));
var filenode = node.Ancestors("File").First();
var tempname = filenode.Element("name");
var filename = tempname.Value.ToString();
var filePassword = filenode.Element("password");
if (filePassword.Value.ToString() == tbPassword.Text)
{
Response.Clear();
Response.ContentType = "application/zip";
Response.AppendHeader("Content-Disposition", "attachment; fileID=" + text);
Response.TransmitFile("C:\\Uploads\\" + filename);
Response.End();
}
The XML Document im saving to looks like this:
<?xml version="1.0" encoding="utf-8"?>
<rootElement>
<File>
<name>Pictures-21-06-2013.zip</name>
<uriID>96e1253b-634b-498a-b062-61a1a097ee3f</uriID>
<password>%zFxRr|</password>
</File>
<File>
<name>Test1-21-06-2013.zip</name>
<uriID>44d3d2c8-5c19-4f79-a5e2-66bb023a4d5e</uriID>
<password>{hik6.e</password>
</File>
Please any suggestions are welcome, and let me know if you would like me to show any other code. Also just to add, when the files are uploaded into the C:\Uploads folder, the zip folders have the date at the end of their names.
Try changing this line to the following:
Response.AppendHeader("content-disposition", "attachment; filename=" + filename);