ジャーナルエントリをテキストファイルにエクスポートできるようにしたいと考えています。すべてのデータを含むファイルを作成することはできますが、ユーザーがコンピュータ上でファイルをダウンロードして保存できるように、特定の場所にファイルを厳密に保存することができます。 StreamWriterでファイルを作成した後、ファイルのダウンロードを強制する方法。私は現在次のコードを持っています:作成したファイルをユーザーのコンピュータに強制的にダウンロードする方法C#
string fileName = "Journal.txt";
using (StreamWriter journalExport = new StreamWriter(fileName))
{
foreach (JournalEntryView entry in journalEnteries)
{
//write each journal entery to file/document
journalExport.WriteLine(entry.timestamp + " - " + entry.author + " (" + entry.authorRole + ")");
journalExport.WriteLine(entry.text);
journalExport.WriteLine("");
journalExport.WriteLine("");
}
}
これをActionResultに入れてファイルを返します。
EDIT:は、次のコードは、私の新しい現在のコードと私が行くことを探しています方向で が、私は、このメソッドを呼び出すActionLinkのを使用する場合、私はちょうどダウンロードするのではなく、新しいページにリダイレクトされますファイル。
string fileName = "Journal.txt";
string filepath = ConfigurationManager.AppSettings["DocumentRoot"] + "\\" + id + "\\" + fileName;
using (StreamWriter journalExport = new StreamWriter(filepath))
{
foreach (JournalEntryView entry in journalEnteries)
{
//write each journal entery to file/document
journalExport.WriteLine(entry.timestamp + " - " + entry.author + " (" + entry.authorRole + ")");
journalExport.WriteLine(entry.text);
journalExport.WriteLine("");
journalExport.WriteLine("");
}
}
byte[] fileData = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = fileName,
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileData, contentType);
あなたは 'FileContentResult'と'ファイル() 'メソッドを見ていましたか? – SLaks
私は持っていますが、私のニーズを達成するためにそれらを使う方法がわかりません –