Un esempio in C#, da usare in ASP.NET, che permette di leggere un file e inviarlo al Browser

C#

/* 
 * using System.IO;
 */
// controllo se il file esiste o meno filePath
if( System.IO.File.Exists(filePath) == true ) 
{
  // forzo la richiesta di salvataggio del file
  string contentType = "application/octet-stream";

  //imposto il corretto contentType in accordo con RFC 2616 e RFC 1806 
  Response.ContentType = contentType;
  
  Response.AppendHeader("Content-Disposition", "attachment; filename=mioNomefile.estensione");

  System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open,
      System.IO.FileAccess.Read, System.IO.FileShare.Read);
      
  try 
  {
    int bufSize = (int)stream.Length;
    byte[] buf = new byte[bufSize];
    
    // leggo il file di origine
    int bytesRead = stream.Read(buf, 0, bufSize);
    stream.Close();

    // lo rispedisco al browser
    Response.OutputStream.Write(buf, 0, bytesRead);
  }
  catch
  {
    // gestire l'errore
  }
} 
Tags:
ASP.NET54 Browser25 C#235 Esempi224
Potrebbe interessarti anche: