I use C#-MVC3. I have an "export" page. I have some functions for exporting different tables from the DB, every function creates a CSV file from the table and returns a FileContentResult file to the user.
Now I want to create a button for "export all", to download all the files at once.
I tried to use ZipFile but it gets only file names and path - files that were saved on the server, not "FileContentResult" files.
So I wanted to save the "FileContentResult" files temporarily on the server, zip them and delete them - but I can't find how to save a "FileContentResult" file.
If you can help me or give me another idea, I'll glad to hear.
my solution:
public ZipFile DownloadAllToZip()
{
string path = "c:\\TempCSV";
try
{
if (Directory.Exists(path))
{
EmptyFolder(path);
}
else
{
DirectoryInfo di = Directory.CreateDirectory(path);
}
List<FileContentResult> filesToExport = GetAllCSVs();
foreach (var file in filesToExport)
{
try
{
using (FileStream stream = new FileStream(path + "\\" + file.FileDownloadName, FileMode.CreateNew))
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
{
byte[] buffer = file.FileContents;
stream.Write(buffer, 0, buffer.Length);
writer.Close();
}
}
}
catch { }
}
}
catch{ }
Response.Clear();
Response.BufferOutput = false;
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=MaterialAssetTracker.zip");
ZipFile zip= new ZipFile();
using (zip)
{
zip.CompressionLevel = CompressionLevel.None;
zip.AddSelectedFiles("*.csv", path + "\\", "", false);
zip.Save(Response.OutputStream);
}
Response.Close();
EmptyFolder(path);
return zip;
}
Related
In my asp mvc 3 application, I have an action which allows the user to download a given file.
Here is the code :
public FilePathResult DownloadFile(string fileName)
{
try
{
string uploadsDocumentPath = System.Configuration.ConfigurationManager.AppSettings["uploadsDocumentPath"].ToString();
string ext = Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); // henter info fra windows registry
if (regKey != null && regKey.GetValue("Content Type") != null)
{
mimeType = regKey.GetValue("Content Type").ToString();
}
return File(uploadsDocumentPath + fileName, mimeType, fileName);
}
catch (Exception)
{
throw;
}
}
I want to be able to allow only files with size less than 150MB to be downloaded. But I can't find how to calculate this type of file's size.
Any ideas ?
I guess this should work:
FileInfo file = new FileInfo(uploadsDocumentPath + fileName);
if(file.Length > 157286400)
{
// Return error here.
}
I can not find where is temporary folder to add temp file into.
How do i find?
You just create your own folder and manage the content:
private void SaveTempFile(string fileName, object data)
{
var storage = IsolatedStorageFile.GetUserStoreForApplication();
if (storage.DirectoryExists("temp") == false)
storage.CreateDirectory("temp");
fileName = Path.Combine("temp", fileName);
using (var fileStream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
{
//Write the data
using (var isoFileWriter = new StreamWriter(fileStream))
{
// write your data in the format of your choice
}
}
}
Delete the file whenever you want to
public void DeleteTempFile(string fileName)
{
try
{
var storage = IsolatedStorageFile.GetUserStoreForApplication();
if (storage.DirectoryExists("temp") == false) return;
fileName = Path.Combine("temp", fileName);
if (storage.FileExists(fileName))
{
storage.DeleteFile(fileName);
}
}
catch (Exception) { }
}
There is no that kind of folder prepared for app on Windows Phone. You have to create it on your own and manage clearing the content form there when it's no longer needed. However you don't need to bother about deleting that files when your app is uninstalled - whole application folder is deleted from isolated storage then.
I am trying to read a text file from IsolatedStorage and check it contains a string. If not, the string is added to the end of the file. But When I am trying to write the string into file I got an error: "Operation not permitted on IsolatedStorageFileStream.". My code shown below. How can I overcome this problem?
public void AddToDownloadList()
{
IsolatedStorageFile downloadFile=IsolatedStorageFile.GetUserStoreForApplication();
try
{
string downloads = string.Empty;
if (!downloadFile.DirectoryExists("DownloadedFiles"))
downloadFile.CreateDirectory( "DownloadedFiles" );
if(downloadFile.FileExists("DownloadedFiles\\DownloadList.txt"))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile("DownloadedFiles\\DownloadList.txt",FileMode.Open, FileAccess.Read );
using ( StreamReader reader = new StreamReader( downloadStream ) )
{
downloads = reader.ReadToEnd();
reader.Close();
}
downloadFile.DeleteFile( "DownloadedFiles\\DownloadList.txt" );
}
downloadFile.CreateFile( "DownloadedFiles\\DownloadList.txt" );
string currentFile = FileName;
if ( !downloads.Contains( currentFile ) )
{
downloads += currentFile;
using ( StreamWriter writeFile = new StreamWriter( new IsolatedStorageFileStream( "DownloadedFiles\\DownloadList.txt", FileMode.Create, FileAccess.Write, downloadFile ) ) )
{
writeFile.Write( currentFile + "," );
writeFile.Close();
}
}
}
catch ( Exception ex )
{
string message = ex.Message;
}
}
I think the problem you were having has to do with the line where you create the StreamWriter by newing up the IsolatedStorageFileStream - when you already should have the right one from the return of the downloadFile.CreateFile() call.
Try this code, I think it does what you want to do:
public static void AddToDownloadList()
{
try
{
AddToDownloadList("DownloadedFiles", "this file name", "DownloadedFiles\\DownloadList.txt");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
}
}
public static void AddToDownloadList(string directory, string fileName, string filePath)
{
string downloads = string.Empty;
using (IsolatedStorageFile downloadFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!downloadFile.DirectoryExists(directory))
downloadFile.CreateDirectory(directory);
if (downloadFile.FileExists(filePath))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile(filePath, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(downloadStream))
{
downloads = reader.ReadToEnd();
reader.Close();
}
}
string currentFile = fileName;
if (!downloads.Contains(currentFile))
{
downloadFile.DeleteFile(filePath);
using (IsolatedStorageFileStream stream = downloadFile.CreateFile(filePath))
{
downloads += currentFile;
using (StreamWriter writeFile = new StreamWriter(stream))
{
writeFile.Write(currentFile + ",");
writeFile.Close();
}
}
}
}
}
I would really appreciate some help with deleting a file from IsolatedStorage on WP7. I am basically downloading a file from the web, storing it in Isolated Storage and then uploading it to my Downloads folder in my Dropbox. Once I have uploaded it, I would like to delete the file from Isolated Storage, but am getting Exception errors when trying to do so.
Here is my code :
public void readCompleteCallback(Object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
//string fileName = txtUrl.Text.Substring(txtUrl.Text.LastIndexOf("/") + 1).Trim();
string fileName = searchBox.Text + fileExt;
//string fileName = "DownloadedNZB.nzb";
bool isSpaceAvailable = IsSpaceIsAvailable(e.Result.Length);
if (isSpaceAvailable)
{
// Save mp3 to Isolated Storage
using (var isfs = new IsolatedStorageFileStream(fileName,
FileMode.CreateNew,
IsolatedStorageFile.GetUserStoreForApplication()))
{
long fileLen = e.Result.Length;
byte[] b = new byte[fileLen];
var numberOfBytesRead = e.Result.Read(b, 0, b.Length);
isfs.Write(b, 0, numberOfBytesRead);
isfs.Flush();
isfs.Close();
isf = IsolatedStorageFile.GetUserStoreForApplication();
stream = isf.OpenFile(fileName, FileMode.Open);
MessageBox.Show("File downloaded successfully");
App.GlobalClient.UploadFileAsync("/Public/", fileName, stream, (response) =>
{
MessageBox.Show("Uploaded file to Dropbox OK.");
},
(error) =>
{
MessageBox.Show(error + "Cannot upload file to dropbox.");
});
}
//stream.Close();
isf.DeleteFile(searchBox.Text + fileExt);
}
else
{
MessageBox.Show("Not enough to space available to download the file");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show(e.Error.Message);
}
}
I cannot think where I am going wrong, but if someone could point me in the right direction, I would appreciate it.
You are trying to delete file inside using statement, where file is not closed yet
UPD: Your upload is async, so you can delete file only when it completed. Put your code near MessageBox.Show("Uploaded file to Dropbox OK.");
This code is supposed to download a file using mvc3 controller
public FilePathResult GetFileFromDisk(String file)
{
String path = AppDomain.CurrentDomain.BaseDirectory + "AppData/";
String contentType = "text/plain";
return File(path+file, contentType, file);
}
View part :
#Html.ActionLink("Download", "GetFileFromDisk","Upload", new { file = "textfile" },null);
But when i click the link I am getting this error
Could not find a part of the path 'D:\Project\FileUploadDownload\FileUploadDownload\AppData\textfile'.
[DirectoryNotFoundException: Could not find a part of the path 'D:\Project\FileUploadDownload\FileUploadDownload\AppData\textfile'.]
Why the foldername is repeating in the file path? Please offer a solution...
Try like this:
public ActionResult GetFileFromDisk(string file)
{
var appData = Server.MapPath("~/App_Data");
var path = Path.Combine(appData, file);
path = Path.GetFullPath(path);
if (!path.StartsWith(appData))
{
// Ensure that we are serving file only inside the App_Data folder
// and block requests outside like "../web.config"
throw new HttpException(403, "Forbidden");
}
if (!System.IO.File.Exists(path))
{
return HttpNotFound();
}
var contentType = "text/plain";
return File(path, contentType, Path.GetFileName(path));
}