Pourquoi ce code ne permet-il pas d’atteindre la première ReadLine à partir d’un StreamReader?

Je transmettais un fichier volumineux dans le premier argument à SendXMLFile () ci-dessous, mais, comme il provoquait le “blocage” / “gel” du périphérique de poche, j’ai temporairement codé en dur un fichier beaucoup plus petit (3 Ko au lieu de 1121 Ko). pour tester.

Le fichier existe bel et bien (dans le même dossier que le fichier .exe / .dll), comme le montre ce 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(Ssortingng.Format("{0} does not seem to exist", fileName)); } else { MessageBox.Show(Ssortingng.Format("{0} DOES seem to exist", fileName)); } ssortingng justFileName = Path.GetFileNameWithoutExtension(fileName); Ssortingng uri = Ssortingng.Format(@"http://SHANNON2:21609/api/inventory/sendXML/gus/woodrow/{0}", justFileName).Trim(); SendXMLFile(fileName, uri, 500); 

Voici le code qui est ensuite appelé pour tenter d’envoyer le fichier:

 public static ssortingng SendXMLFile(ssortingng xmlFilepath, ssortingng uri, int timeout) { // TODO: Remove after testing Ssortingng s = Ssortingng.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"); } . . . 

Quand je lance ceci, je vois:

 "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" 

– mais pas le message ” line == … ” – il se bloque et je dois redémarrer à chaud le périphérique pour le ramener des limbes électroniques.

Y at-il un problème potentiel avec le code StreamReader, ou … ???

METTRE À JOUR

Je ne sais pas s’il s’agit d’un problème dans les données ou d’une différence que j’ai dû faire dans le code pour le faire fonctionner dans le Compact Framework. J’ai un code très similaire qui fonctionne à partir d’une application Winforms:

 public static ssortingng SendXMLFile(ssortingng xmlFilepath, ssortingng uri, int timeout) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; request.ContentType = "application/xml"; request.Method = "POST"; SsortingngBuilder sb = new SsortingngBuilder(); using (StreamReader sr = new StreamReader(xmlFilepath)) { Ssortingng line; while ((line = sr.ReadLine()) != null) { sb.AppendLine(line); } byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToSsortingng()); 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; } } } 

— appelé comme ça, en passant le même fichier comme cas de test:

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

MISE À JOUR 2

J’ai changé le code pour utiliser un XMLTextReader, et maintenant je reviens à l’erreur que j’avais précédemment, à savoir “(400) Bad Request” qui est documentée dans la plupart de ses détails sanglants ici .

Voici le nouveau code, et ce que je vois maintenant:

public statique bool WriteIt2 (chaîne nomFichier, données chaîne, taille longue) {bool retVal = false; int bytRd = 0; // si vous utilisez ceci, changez son nom ssortingng 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(Ssortingng.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); 

Maintenant, voici le code qui lit, écrit et envoie (ou tente de):

 public static ssortingng SendXMLFile(ssortingng xmlFilepath, ssortingng uri, int timeout) { Ssortingng s = Ssortingng.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(""); 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(""); break; } } // TODO: Remove after testing MessageBox.Show("Made it past the while loop"); MessageBox.Show(Ssortingng.Format("sb first line is {0}", sb[0].ToSsortingng())); MessageBox.Show(Ssortingng.Format("sb tenth line is {0}", sb[9].ToSsortingng())); byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToSsortingng()); 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; } } 

Ce que je vois maintenant quand ça marche:

 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 "" 8) "The remote server returned an error (400) Bad Request" 

Donc au moins, ça ne tient plus, mais je me demande pourquoi le serveur considère cela comme une mauvaise requête.

Je pense que vous devriez revenir à l’essentiel:

 public static ssortingng SendXMLFile(ssortingng xmlFilepath, ssortingng 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.GetSsortingng(response); } } 

et voyez ce qui fonctionne et ce que le serveur pense de votre fichier.

Quand vous avez vraiment besoin d’un TimeOut, voyez cette réponse