Why does this code hang on reaching the first ReadLine from a StreamReader?

风流意气都作罢 提交于 2019-12-04 07:16:38

问题


I was passing a large file in the first arg to SendXMLFile() below but, since it was causing the handheld device to "hang"/"freeze" I temporarily hard-coded a much smaller file (3 KB as opposed to 1121 KB) for testing.

The file does indeed exist (in the same folder as the .exe/.dll), as can be seen by this code:

// test with smaller file:
fileName = "DSD_v6666_3_20140310140737916.xml";
MessageBox.Show("Made it before file.Open");
using (FileStream fileTest = File.Open(fileName, FileMode.CreateNew)) 
{
    fileTest.Write(info, 0, info.Length);
    fileTest.Flush();
}
if (!File.Exists(fileName))
{
    MessageBox.Show(String.Format("{0} does not seem to exist", fileName));
} 
else
{
    MessageBox.Show(String.Format("{0} DOES seem to exist", fileName));
}

string justFileName = Path.GetFileNameWithoutExtension(fileName);
String uri = String.Format(@"http://SHANNON2:21609/api/inventory/sendXML/gus/woodrow/{0}", justFileName).Trim();
SendXMLFile(fileName, uri, 500);

Here is the code that is then called, attempting to send the file:

public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
    // TODO: Remove after testing
    String s = String.Format("xmlFilepath == {0}, uri == {1}, timeout == {2}", xmlFilepath, uri, timeout);
    MessageBox.Show(s);
    // </ TODO: Remove after testing

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

    //request.KeepAlive = false; // should this be true? <== commented out as a test, but no diff in behavior
    request.ProtocolVersion = HttpVersion.Version10;
    request.ContentType = "application/xml";
    request.Method = "POST";

    StringBuilder sb = new StringBuilder();
    // TODO: Remove after testing
    MessageBox.Show("Made it to just before the StreamReader using");
    using (StreamReader sr = new StreamReader(xmlFilepath))
    {
        // TODO: Remove after testing
        MessageBox.Show("Made it just inside the StreamReader using"); // <= This is the last point reached 
        String line;
        while ((line = sr.ReadLine()) != null)
        {
            // TODO: Remove after testing
            MessageBox.Show(string.Format("line == {0}", line));
            sb.Append("\r\n");
        }
        . . .

When I run this, I see:

"Made it before file.Open"
"DSD_v6666_3_20140310140737916.xml DOES seem to exist"
[The xmlFilepath, uri, and timout vals expected]
"Made it to just before the StreamReader using"
"Made it just inside the StreamReader using"

-- but not the "line == ..." message - it hangs, and I have to warm boot the device to bring it back from electronic limbo.

Is there a potential problem with the StreamReader code, or...???

UPDATE

I don't know whether this is a problem is in the data, or a differences I had to make in the code to get it to work in the Compact Framework. I have very similar code that works from a Winforms app:

public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

    request.KeepAlive = false;
    request.ProtocolVersion = HttpVersion.Version10;
    request.ContentType = "application/xml";
    request.Method = "POST";

    StringBuilder sb = new StringBuilder();
    using (StreamReader sr = new StreamReader(xmlFilepath))
    {
        String line;
        while ((line = sr.ReadLine()) != null)
        {
            sb.AppendLine(line);
        }
        byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());

        if (timeout < 0)
        {
            request.ReadWriteTimeout = timeout;
            request.Timeout = timeout;
        }

        request.ContentLength = postBytes.Length;

        try
        {
            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            //using (var response = (HttpWebResponse)request.GetResponse())
            //{
            //    return response.ToString();
            //}
            // alternate way, safe for older versions of .NET
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse(); 
            }
            finally
            {
                IDisposable disposableResponse = response as IDisposable;
                if (disposableResponse != null) disposableResponse.Dispose();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            request.Abort();
            return string.Empty;
        }
    }
}

---called like so, passing the same file as a test case:

private void button20_Click(object sender, EventArgs e)
{
    // Change the file name before each test
    String fullFilePath = @"C:\HoldingTank\DSD_v6666_3_20140310140737916.xml";
    string justFileName = Path.GetFileNameWithoutExtension(fullFilePath);
    String uri = String.Format(@"http://localhost:21608/api/inventory/sendXML/su/su/{0}", justFileName);
    SendXMLFile(fullFilePath, uri, 500);
}

UPDATE 2

I changed the code to use an XMLTextReader, and now I'm back to the err I was previously having, namely "(400) Bad Request" which is documented in most of its gory detail here.

Here is the new code, and what I now see:

public static bool WriteIt2( string fileName, string data, long fsize ) { bool retVal = false; int bytRd = 0; // if use this, change its name string the_Msg = "";

if (File.Exists(fileName))
{
    File.Delete(fileName);
}

Byte[] info = Encoding.UTF8.GetBytes(data);
// Testing with this relatively small file for now
fileName = "DSD_v6666_3_20140310140737916.xml";
MessageBox.Show("Made it before file.Open");
using (FileStream fileTest = File.Open(fileName, FileMode.CreateNew)) 
{
    fileTest.Write(info, 0, info.Length);
    fileTest.Flush();
}
if (!File.Exists(fileName))
{
    MessageBox.Show(String.Format("{0} does not seem to exist", fileName));
} // I have never seen the msg above, but always saw the one below, so commented it out
else //<= always exists, so unnecessary
{
    MessageBox.Show(String.Format("{0} DOES seem to exist", fileName));
}

string justFileName = Path.GetFileNameWithoutExtension(fileName);
String uri = String.Format(@"http://SHANNON2:21609/api/inventory/sendXML/su/su/{0}", justFileName).Trim();

SendXMLFile(fileName, uri, 500);

Now here's the code that actually does the reading, writing, and sending (or tries to):

public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
    String s = String.Format("xmlFilepath == {0}, uri == {1}, timeout == {2}", xmlFilepath, uri, timeout);
    MessageBox.Show(s);
    // </ TODO: Remove after testing

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

    request.ProtocolVersion = HttpVersion.Version10;
    request.ContentType = "application/xml";
    request.Method = "POST";

    StringBuilder sb = new StringBuilder();
    MessageBox.Show("Made it to just before the StreamReader using");

    StreamReader sr = new StreamReader(xmlFilepath);
    MessageBox.Show("Made it past the StreamReader being constructed");
    XmlTextReader reader = null;    
    reader = new XmlTextReader(sr);
    while (reader.Read()) 
    {
        switch (reader.NodeType) 
        {
            case XmlNodeType.Element: // The node is an Element.
                sb.Append("<" + reader.Name);
            while (reader.MoveToNextAttribute()) // Read attributes.
                sb.Append(" " + reader.Name + "='" + reader.Value + "'");
                sb.Append(">");
                sb.Append(">");
                break;
            case XmlNodeType.Text: //Display the text in each element.
                sb.Append (reader.Value);
                break;
            case XmlNodeType. EndElement: //Display end of element.
                sb.Append("</" + reader.Name);
                sb.Append(">");
                break;
        }
    }
    // TODO: Remove after testing
    MessageBox.Show("Made it past the while loop");
    MessageBox.Show(String.Format("sb first line is {0}", sb[0].ToString()));
    MessageBox.Show(String.Format("sb tenth line is {0}", sb[9].ToString()));
    byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());

    if (timeout < 0)
    {
        request.Timeout = timeout;
    }

    request.ContentLength = postBytes.Length;

    try
    {
        Stream requestStream = request.GetRequestStream();

        requestStream.Write(postBytes, 0, postBytes.Length);
        requestStream.Close();

        // This code for older versions of .NET from ctacke:
        HttpWebResponse response = null;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
            return response.ToString();
        }
        finally
        {
            IDisposable disposableResponse = response as IDisposable;
            if (disposableResponse != null) disposableResponse.Dispose();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        request.Abort();
        return string.Empty;
    }
}

What I see now when this runs:

0) "Made it before file.Open"
1) "DSD_v6666_3_20140310140737916.xml DOES seem to exist"
2) [ the xmlFilePath and other args - they are what is expected ]
3) "Made it to just before the StreamReader using"
4) "Made it past the StreamReader being constructed
5) "Made it past the while loop
6) "sb first line is "<"
7) "sb tenth line is ">"
8) "The remote server returned an error (400) Bad Request"

So at least it's no longer hanging, but I'm back to wondering why the server considers this a bad request.


回答1:


I think you should return to basics:

public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
    using (var client = new WebClient())
    {                
        client.Headers.Add("Content-Type", "application/xml");                
        byte[] response = client.UploadFile(uri, "POST", xmlFilepath);
        return Encoding.ASCII.GetString(response);
    }
}

and see what works and what the server thinks of your file.

When you really need a TimeOut then see this answer



来源:https://stackoverflow.com/questions/25557930/why-does-this-code-hang-on-reaching-the-first-readline-from-a-streamreader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!