我在一个实例中成功地将字符串保存为文件的内容,而在另一个实例中,它失败了。为什么呢?
以下是成功尝试的代码(创建名为&#34的文件; platypi.xml"将原始文件中的内容(位于手持设备上)创建为服务器/ PC上的新文件:
public enum HttpMethods
{
GET = 0,
PUT,
POST,
DELETE,
HEAD,
OPTIONS,
LIST,
UNKNOWN
}
private void menuItem2_Click(object sender, System.EventArgs e)
{
String uri = "http://192.168.125.50:21608/api/inventory/sendXML/duckbill/platypus/platypi";
RESTfulMethods rm = new RESTfulMethods();
rm.SendXMLFile(uri);
}
public void SendXMLFile(string uri)
{
StringBuilder sb = new StringBuilder();
StreamReader sr = new StreamReader(@"\My Documents\heavens2Murgatroid.XML");
String line;
while ((line = sr.ReadLine()) != null)
{
sb.Append(line);
sb.Append("\r\n");
}
sr.Close();
string strData = @sb.ToString();
strData = strData.Replace("\"", "'"); // <= Needed?
CreateRequestNoCredentials(uri, HttpMethods.POST, strData, "application/xml");
}
public static HttpWebRequest CreateRequestNoCredentials(string uri, HttpMethods method, string data, string contentType)
{
WebRequest request = WebRequest.Create(uri);
try
{
request.Method = Enum.ToObject(typeof(HttpMethods), method).ToString();
request.ContentType = contentType;
((HttpWebRequest)request).Accept = contentType;
((HttpWebRequest)request).KeepAlive = false;
((HttpWebRequest)request).ProtocolVersion = HttpVersion.Version10;
if (method != HttpMethods.GET && method != HttpMethods.DELETE)
{
byte[] arrData = Encoding.UTF8.GetBytes(data);
request.ContentLength = arrData.Length;
using (Stream oS = request.GetRequestStream())
{
oS.Write(arrData, 0, arrData.Length);
}
}
else
{
request.ContentLength = 0;
}
}
catch (WebException webex)
{
HttpWebResponse hwr = (HttpWebResponse) webex.Response;
HttpStatusCode hsc = hwr.StatusCode;
MessageBox.Show(string.Format("{0} Status code == {1}", webex.Message, hsc.ToString()));
}
return request as HttpWebRequest;
}
以下是不成功尝试的代码:
// This code also uses the HttpMethods enum
public static void WriteIt2(string fileName, string data)
{
// "data" does contain valid data here; fileName is also a valid name
if (File.Exists(fileName))
{
MessageBox.Show(String.Format("{0} exists - deleting", fileName));
File.Delete(fileName);
}
string justFileName = Path.GetFileNameWithoutExtension(fileName);
String uri = String.Format("http://192.168.125.50:21608/api/inventory/sendXML/duckbill/platypus/{0}", justFileName);
String bla = data.Substring(0, 102);
MessageBox.Show(String.Format("uri is {0}; first part of data is {1}", uri, bla));
// I do see the first part of data here in the MessageBox ("bla" and thus "data" are not empty)
CreateRequestNoCredentials(uri, HttpMethods.POST, data, "application/xml");
}
// CreateRequestNoCredentials() is the same as that shown above
在这种情况下,保存文件(名为&#34; [fileName]&#34;),但文件为空。有什么区别?
答案 0 :(得分:1)
我看到的唯一区别是第一组代码将更改后的字符串文字传递给CreateRequestNoCredentials()方法。 string strData = @ sb.ToString();不确定你传递给WriteIt2方法的是什么。