2009-09-03 15 views
21

Tengo que crear y devolver el archivo en mi aplicación ASP.net MVC. El tipo de archivo debe ser un archivo .txt normal. Sé que puedo devolver FileResult pero no sé cómo usarlo.Cómo crear un archivo y devolverlo a través de FileResult en ASP.NET MVC?

public FilePathResult GetFile() 
{ 
string name = "me.txt"; 

FileInfo info = new FileInfo(name); 
if (!info.Exists) 
{ 
    using (StreamWriter writer = info.CreateText()) 
    { 
     writer.WriteLine("Hello, I am a new text file"); 

    } 
} 

return File(name, "text/plain"); 
} 

Este código no funciona. ¿Por qué? ¿Cómo hacerlo con el resultado de la secuencia?

Respuesta

31

EDITAR (Si desea que el flujo intente esto:)

public FileStreamResult GetFile() 
{ 
    string name = "me.txt"; 

    FileInfo info = new FileInfo(name); 
    if (!info.Exists) 
    { 
     using (StreamWriter writer = info.CreateText()) 
     { 
      writer.WriteLine("Hello, I am a new text file"); 

     } 
    } 

    return File(info.OpenRead(), "text/plain"); 

} 

Usted podría intentar algo como esto ..

public FilePathResult GetFile() 
{ 
    string name = "me.txt"; 

    FileInfo info = new FileInfo(name); 
    if (!info.Exists) 
    { 
     using (StreamWriter writer = info.CreateText()) 
     { 
      writer.WriteLine("Hello, I am a new text file"); 

     } 
    } 

    return File(name, "text/plain"); 

} 
+3

Considere también las otras opciones: http://stackoverflow.com/questions/1187261/whats-the-difference-between-the-four-file-results-in-asp-net-mvc recordando ese archivo (puede acomodar todos ellos. – RichardOD

+0

esto no funciona, así que deshice el signo "nike" – Ante

+0

Sí, el archivo ([params], ...) hará lo que quiera ... necesita averiguar lo que quiere ... – BigBlondeViking

8

Abrir el archivo en una StreamReader, y pasar la corriente como un argumento a la FileResult:

public ActionResult GetFile() 
{ 
    var stream = new StreamReader("thefilepath.txt"); 
    return File(stream.ReadToEnd(), "text/plain"); 
} 
+1

Tenga en cuenta que ' "thefilepath.txt"' tiene que ser la ruta completa al archivo de texto, no solo a una ruta relativa. –

+0

¿cómo puedo crear uno? con "TextWriter tw = new StreamWriter (" date.txt ");" ¿o algo mas? – Ante

+1

Sí, por ejemplo, me gusta. Recuerde que las rutas de archivos deben ser rutas completas y usar declaraciones 'using'. –

1

Otro ejemplo de la creación y la descarga de archivos de la aplicación ASP .NET MVC a la vez, pero el contenido del archivo se crea en la memoria (RAM) - sobre la marcha:

public ActionResult GetTextFile() 
{ 
    UTF8Encoding encoding = new UTF8Encoding(); 
    byte[] contentAsBytes = encoding.GetBytes("this is text content"); 

    this.HttpContext.Response.ContentType = "text/plain"; 
    this.HttpContext.Response.AddHeader("Content-Disposition", "filename=" + "text.txt"); 
    this.HttpContext.Response.Buffer = true; 
    this.HttpContext.Response.Clear(); 
    this.HttpContext.Response.OutputStream.Write(contentAsBytes, 0, contentAsBytes.Length); 
    this.HttpContext.Response.OutputStream.Flush(); 
    this.HttpContext.Response.End(); 

    return View(); 
} 
Cuestiones relacionadas