?
Solved

C# - Downloading file adding extra data (unintentionally)

Posted on 2012-03-26
13
Medium Priority
?
461 Views
Last Modified: 2012-04-01
The problem I have is that I am downloading data via WCF but it is adding to the text file.

THE DATA SHOULD LOOKE LIKE BELOW

Record Count 14866
"Field"      "Type"      "Length"
"oldparent"      "Text"      "8"
"NEWPARENT"      "Text"      "8"
"PID"      "Text"      "8"
"STATUS_BLD"      "Text"      "1"
"DATE"      "Text"      "8"
"CREASON"      "Text"      "1"
"MPID"      "Text"      "8"
"NAME"      "Text"      "30"
"STREET"      "Text"      "24"
"CITY"      "Text"      "16"
"STATE"      "Text"      "2"
"ZIPCODE"      "Text"      "7"

BUT I AM GETTING

Record Count 14866
"Field"      "Type"      "Length"
"oldparent"      "Text"      "8"
"NEWPARENT"      "Text"      "8"
"PID"      "Text"      "8"
"STATUS_BLD"      "Text"      "1"
"DATE"      "Text"      "8"
"CREASON"      "Text"      "1"
"MPID"      "Text"      "8"
"NAME"      "Text"      "30"
"STREET"      "Text"      "24"
"CITY"      "Text"      "16"
"STATE"      "Text"      "2"
"ZIPCODE"      "Text"      "7"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head><title>
      Download
</title><link rel="icon" href="images/favicon.ico" type="image/ico" /><link href="Styles/Site.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .style7
        {
            width: 42%;
        }
    </style>

ETC.....

Below is the code I am using.  

Response.BufferOutput = false;
byte[] buffer = new byte[65000];
int bytesRead = 0;

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition",
                        "attachment; filename=" + requestData.FileName);

bytesRead = fileInfo.FileByteStream.Read(buffer, 0, buffer.Length);

while (bytesRead > 0)
{
    // Verify that the client is connected.
    if (Response.IsClientConnected)
    {
        Response.OutputStream.Write(buffer, 0, bytesRead);
        // Flush the data to the HTML output.
        Response.Flush();

         buffer = new byte[65000];
         bytesRead = fileInfo.FileByteStream.Read(buffer, 0, buffer.Length);
     }
     else
     {
           bytesRead = -1;
      }
}
Response.Flush();

How do I fix?
0
Comment
Question by:CipherIS
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 4
13 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 37771394
I don't quite understand what you are intending to return in the web service call...
0
 
LVL 1

Author Comment

by:CipherIS
ID: 37771423
I am returning a text file.  This is the data in the text file.

Record Count 14866
"Field"      "Type"      "Length"
"oldparent"      "Text"      "8"
"NEWPARENT"      "Text"      "8"
"PID"      "Text"      "8"
"STATUS_BLD"      "Text"      "1"
"DATE"      "Text"      "8"
"CREASON"      "Text"      "1"
"MPID"      "Text"      "8"
"NAME"      "Text"      "30"
"STREET"      "Text"      "24"
"CITY"      "Text"      "16"
"STATE"      "Text"      "2"
"ZIPCODE"      "Text"      "7"

This is what is being returned in the text file

Record Count 14866
"Field"      "Type"      "Length"
"oldparent"      "Text"      "8"
"NEWPARENT"      "Text"      "8"
"PID"      "Text"      "8"
"STATUS_BLD"      "Text"      "1"
"DATE"      "Text"      "8"
"CREASON"      "Text"      "1"
"MPID"      "Text"      "8"
"NAME"      "Text"      "30"
"STREET"      "Text"      "24"
"CITY"      "Text"      "16"
"STATE"      "Text"      "2"
"ZIPCODE"      "Text"      "7"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head><title>
      Download
</title><link rel="icon" href="images/favicon.ico" type="image/ico" /><link href="Styles/Site.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .style7
        {
            width: 42%;
        }
    </style>

ETC.....

Some how this is being appended to the text file and it shouldn't be.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head><title>
      Download
</title><link rel="icon" href="images/favicon.ico" type="image/ico" /><link href="Styles/Site.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .style7
        {
            width: 42%;
        }
    </style>

ETC.....
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 37771453
What type of WCF service is this?

Instead of application/octet-stream, did you try text/plain?
0
Veeam Task Manager for Hyper-V

Task Manager for Hyper-V provides critical information that allows you to monitor Hyper-V performance by displaying real-time views of CPU and memory at the individual VM-level, so you can quickly identify which VMs are using host resources.

 
LVL 1

Author Comment

by:CipherIS
ID: 37771624
I replaced with text/plain and still getting below added to it.  Didn't work.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head><title>
      Download
</title><link rel="icon" href="images/favicon.ico" type="image/ico" /><link href="Styles/Site.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .style7
        {
            width: 42%;
        }
    </style>

ETC.....
0
 
LVL 1

Author Comment

by:CipherIS
ID: 37771669
Another thing I need to mention is that the download downloads other file types such as:

PDF and XLS
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 37771735
What type of WCF web service are you working with?
0
 
LVL 1

Author Comment

by:CipherIS
ID: 37771892
basicHTTPBinding.  

The webservice works fine.  It returns all the files.  The only issue is when the text file is being downloaded it adds the HTML code to the text file.

Here is the code in the WCF Service that returns the file

public RemoteFileInfo APIDownloadFile(DownloadRequest request)
{
      string UNCPath = string.Empty;

      RemoteFileInfo result = new RemoteFileInfo();

      try
      {

            string WriteError = Path.Combine(@"C:\Logs\APIFulfillment", "APIDownloadFile.txt");
            using (StreamWriter outfile2 = new StreamWriter(WriteError))
            {
                  //Get Path and FileName
                  UNCPath = APIGetUNCPath(request.AccessKey, request.FileName);
                  outfile2.WriteLine(UNCPath + " | " + DateTime.Now, Environment.NewLine);

                  FileInfo fileInfo = new FileInfo(UNCPath);
                  outfile2.WriteLine("fileInfo" + " | " + DateTime.Now);

                  //Check if exists
                  if (!fileInfo.Exists)
                  {
                        throw new System.IO.FileNotFoundException("File not found", request.FileName);
                  }
                  request.FileSize = fileInfo.Length;
                  outfile2.WriteLine("File Exists" + " | " + DateTime.Now, Environment.NewLine);

                  //Open stream
                  FileStream stream = new FileStream(UNCPath, FileMode.Open, FileAccess.Read);
                  outfile2.WriteLine("FileStream" + " | " + DateTime.Now, Environment.NewLine);

                  //Return result
                  result.FileName = request.FileName;
                  result.Length = fileInfo.Length;
                  result.FileByteStream = stream;
                  outfile2.WriteLine("Result" + " | " + DateTime.Now, Environment.NewLine);

                  //Close the stream to prevent file access denied issue
                  OperationContext.Current.OperationCompleted += (sender, args) =>
                  {
                        if (result.FileByteStream != null)
                        {
                              result.FileByteStream.Dispose();
                        }
                  };
                  outfile2.WriteLine("Close" + " | " + DateTime.Now, Environment.NewLine);
                  outfile2.Close();
            }
      }
      catch (Exception ex)
      {
            //Need to write Error someplace
            string s = ex.Message;

            string WriteError2 = Path.Combine(@"C:\Logs\APIFulfillment", "APIDownloadFile_Error.txt");
            using (StreamWriter outfile = new StreamWriter(WriteError2))
            {
                  outfile.WriteLine(s + " | " + DateTime.Now, Environment.NewLine);
                  outfile.Close();
            }
      }

      return result;
}
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 37772037
Have you thought about Streaming?

How to: Enable Streaming
http://msdn.microsoft.com/en-us/library/ms789010.aspx
0
 
LVL 22

Expert Comment

by:ambience
ID: 37772264
The problem does not look like with the service return but the way you are returning the file to the client. It looks like the Master Page/Layout gets rendered after you output the file.

I'm not sure about the best way to inhibit page rendering from a particular callback. Try calling Response.End right after you flush

Response.Flush();
Response.End();
0
 
LVL 1

Author Comment

by:CipherIS
ID: 37772857
@ambience - Response.End() causes an error.
0
 
LVL 1

Author Comment

by:CipherIS
ID: 37774412
Does anyone have an answer?
0
 
LVL 1

Accepted Solution

by:
CipherIS earned 0 total points
ID: 37774621
I figured it out.  Below is the solution.

                    //Determine how to write the file
                    switch (ext.ToLower())
                    {
                        case ".txt":
                            Response.BinaryWrite(buffer);
                            break;
                        default:
                            Response.OutputStream.Write(buffer, 0, bytesRead);
                            break;
                    }
0
 
LVL 1

Author Closing Comment

by:CipherIS
ID: 37792777
I figured it out.
0

Featured Post

Tutorials alone can't teach real engineering

So we built better training tools.

-Hands-on Labs
-Instructor Mentoring
-Scenario-Based Tests
-Dedicated Cloud Servers

All at your fingertips. What are you waiting for?

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question