.NET 웹 사이트에서 텍스트 파일을 생성하는 가장 좋은 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/129927

문제

VB.NET 웹 응용 프로그램에 페이지가있어 많은 데이터를 텍스트 파일에 던지고 다운로드 할 수 있도록 사용자에게 제시해야합니다. .NET 웹 서버에서 이러한 텍스트 파일을 빌드하는 가장 / 가장 효율적인 방법은 무엇입니까?

편집 : 아래 질문에 답하기 위해, 이것은 한 번 다운로드 한 다음 파일을 던질 것입니다.

업데이트 : John Rudy와 Davidk의 제안을 함께 붙였습니다. 감사합니다!

도움이 되었습니까?

해결책

잊혀진 세미콜론에서 언급 한 바와 같이 반복 된 다운로드 또는 한 번의 닥실이 필요한지 여부에 따라 답이 있습니다.

어느 쪽이든, 키는 출력의 컨텐츠 유형을 설정하여 다운로드 창이 표시되도록하는 것입니다. 직선 텍스트 출력의 문제점은 브라우저가 자체 창에 데이터를 표시하려고한다는 것입니다.

텍스트가 출력 문자열이고 파일 이름이 파일을 (로컬)로 저장하려는 기본 이름이라고 가정 할 때 컨텐츠 유형을 설정하는 핵심 방법은 다음과 비슷합니다.

HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ContentType = "application/octet-stream";
response.Charset = "";
response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", filename));
response.Flush();
response.Write(text);
response.End();

이렇게하면 사용자를위한 다운로드가 제기됩니다.

이제 웹 서버에 문자 그대로 파일을 저장해야한다면 까다로워 지지만 몹시 그렇지는 않습니다. 거기에서 System.io의 클래스를 사용하여 텍스트 파일에 텍스트를 작성하고 싶습니다. 네트워크 서비스, IUSR_MACHINENAME 및 ASPNET Windows 사용자가 쓰는 경로를 작성할 수 있는지 확인하십시오. 그렇지 않으면 동일한 거래 - 콘텐츠 유형과 헤더를 사용하여 다운로드를 보장합니다.

필요하지 않으면 문자 그대로 파일을 저장하지 않는 것이 좋습니다. 심지어 서버에서 직접 수행하는 기술은 올바른 아이디어가 아닐 수도 있습니다. (예 : 해당 파일을 다운로드하기 위해 액세스 제어가 필요한 경우 어떻게해야합니까? 이제 호스팅 환경에 따라 앱 루트 외부에서이를 수행해야합니다.)

따라서 일회성 또는 파일 매력적인 모드에 있는지 알지 못하고 보안 영향을 모르고 (서버 측면 저장이 필요한 경우 스스로 해결해야 할 것입니다), 그게 문제입니다. 내가 줄 수있는 최선의.

다른 팁

StringBuilder를 사용하여 파일의 텍스트를 작성한 다음 Content-Disposition을 사용하여 사용자에게 보냅니다.

여기에 찾은 예 :http://www.eggeadcafe.com/community/aspnet/17/76432/use-the-contentdispositi.aspx

private void Button1_Click(object sender, System.EventArgs e)
{
        StringBuilder output = new StringBuilder;
        //populate output with the string content
        String fileName = "textfile.txt";

        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.WriteFile(output.ToString());

}

Don't build it at all, use an HttpHandler and serve the text file direct into the output stream:

http://digitalcolony.com/labels/HttpHandler.aspx

The code block halfway down is a good example, you can adjust to your own:

public void ProcessRequest(HttpContext context)
{
   response = context.Response;
   response.ContentType = "text/xml";       
   using (TextWriter textWriter = new StreamWriter(response.OutputStream, System.Text.Encoding.UTF8))
   {
       XmlTextWriter writer = new XmlTextWriter(textWriter);
       writer.Formatting = Formatting.Indented;
       writer.WriteStartDocument();
       writer.WriteStartElement("urlset");
       writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
       writer.WriteAttributeString("xsi:schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");
       writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");

       // Add Home Page
       writer.WriteStartElement("url");
       writer.WriteElementString("loc", "http://example.com");
       writer.WriteElementString("changefreq", "daily");
       writer.WriteEndElement(); // url

       // Add code Loop here for page nodes
       /*
       {
           writer.WriteStartElement("url");
           writer.WriteElementString("loc", url);
           writer.WriteElementString("changefreq", "monthly");
           writer.WriteEndElement(); // url
       }
       */
       writer.WriteEndElement(); // urlset
   }                      
}

Bear in mind it doesn't ever need to be a 'file' at the server end. It's the client which turns it into a file.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top