在C#中使用HttpWebRequest自动上传文件的问题 [英] Problem to upload a file automatically using HttpWebRequest in C#

查看:87
本文介绍了在C#中使用HttpWebRequest自动上传文件的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在开发一个类,它会自动将一些文件上传到一个接受该文件作为输入和上传的应用程序。我正在使用HttpWebRequest对象将请求发送到应用程序。


代码如下,但是在文件没有上传到服务器的同时仍然没有给出任何错误。


public static < font size = 2> string Authenticate()


{


尝试


{


HttpWebRequest httpRequest =


(HttpWebRequest)WebRequest.Create(Constant.LiveLinkURL);



httpRequest.Method =" POST";


httpRequest.ContentType = "应用/ X WWW的窗体-urlencoded英寸;


string auth =" func = ll.login& Username =" + Constant.UserID +"& Password =" + Constant.Password;


string next_url =" /tepate-f/livelink.exe?Redirect = 1";


string currentTime =" D /" + DateTime.Now.Year +" /" + DateTime.Now.Month +" /" + DateTime.Now.Day +


":" + DateTime.Now.Hour +":" + DateTime.Now.Minute +":" + DateTime.Now.Second;


string login_url = auth +"& CurrrentClientTime =" + currentTime +"& nextURL =" + next_url;


byte [] bytedata = Encoding.UTF8.GetBytes(login_url);


httpRequest.ContentLength = bytedata.Length;


Stream requestStream = httpRequest.GetRequestStream();


requestStream.Write(bytedata,0,bytedata.Length);


requestStream.Close();



HttpWebResponse httpWebResponse =


(HttpWebResponse)httpRequest.GetResponse();


< font face ="Tahoma,Helvetica,Sans-Serif"> Stream responseStream = httpWebResponse.GetRespo nseStream();


StringBuilder sb = new StringBuilder();


使用 < font face ="Tahoma,Helvetica,Sans-Serif">(StreamReader reader =


new StreamReader(responseStream,System.Text.Encoding.UTF8))


{


string line;


((行= reader.ReadLine())!= null


{


sb.Append(line);


}


}



int headerCount = httpWebResponse.Headers.Count;


string cookie ="" ;;


string 服务r ="";


string connection ="" ;;


for int i = 0; i< headerCount; i ++)


{


if (httpWebResponse.Headers.Keys .ToString()==" Set-Cookie" )


{


cookie = httpWebResponse.Headers +" ;; " ;;


}


else if (httpWebResponse.Headers.Keys .ToString()==" Server")


{


server = httpWebResponse.Headers ;


}


else if (httpWebResponse.Headers.Keys .ToS tring()==" Connection" )


{


connection = httpWebResponse.Headers ;


}


}


char [] sep = {','};


string [] cookieValue = cookie .Split(sep );


string < font size = 2> cookie1 =" LLInProgress =; " ;;


string llcookie ="" ;;


for int i = 0; i< cookieValue.Length; i ++)


{


if (cookieValue .StartsWith(" LLCookie"))


{


llcookie =" LLCookie =" + cookieValue .Substring(" LLCookie =" .Length,cookieValue .IndexOf(" ;;") - " LLCookie =" .Length + 2);


cookie1 + = llcookie;


}


}


cookie1 + =" LLTZCookie = 0" ;;


return cookie1;


}


catch (Exception exObj)


{


int index = exObj.Message.IndexOf("无法将数据写入传输连接");


if ( exObj.Message.IndexOf("无法将数据写入传输连接")> = 0)


{


return "错误:无效网址 - " + Constant.LiveLinkURL;


}


return "错误:" + exObj.Message;


}


}


public static void uploadFile()


{


cookie = Authenticate(); //从OS身份验证中获取cookie


if (cookie.StartsWith(" Error:"))


{


Console.WriteLine( cookie);


return ;


}

boundary = Guid.NewGuid()。ToString( ).Replace(" - ","")。Substring(0,15);


string nextURL =" / teamepns -f / livelink .EXE?重定向= 1英寸;


HttpWebRequest objOSLoginWebRequest =(HttpWebRequest)WebRequest.Create(" http://sww-knowledge-epe.shell.com/teamepns- F / livelink.exe FUNC = 11&安培; OBJTYPE = 144&安培; nextURL = QUOT; + nextURL +"& objAction = create& parentId = 20553784");


objOSLoginWebRequest.ContentType = " application / x-www-form-urlencoded";


objOSLoginWebRequest.Credentials = CredentialCache.DefaultCredentials;


objOSLoginWebRequest.Headers.Set(" Cookie",Cookie);


objOSLoginWebRequest.KeepAlive = true ;



HttpWebResponse httpWebResponse =


(HttpWebResponse)objOSLoginWebRequest.GetResponse();


流responseStream = httpWebResponse.GetResponseStream();


StringBuilder sb = new StringBuilder();


使用 (StreamReader reader =


new StreamReader( responseStream,System.Text.Encoding.UTF8))


{


string 行;


while ((line = reader.ReadLine())!= null


{


sb.Append(line );


}


}



string filePath =" C:\\Ameer \\PerfMon\\llperfmon-teamepns \\uploads\\TEST_DOC_001.txt" ;;


objOSLoginWebRequest = null ;


HttpWebRequest objWebRequest =(HttpWebRequest)WebRequest.Create(" http://sww-knowledge-epe.shell.com/teamepns-f/livelink.exe");


objWebRequest.Headers.Set(" Cookie",Cookie);


objWebRequest.ContentType =" multipart / form-data;边界= QUOT; +边界;


objWebRequest.Credentials = CredentialCache.DefaultCredentials;


objWebRequest.AllowWriteStreamBuffering = true ;


objWebRequest.AllowAutoRedirect = true ;


objWebRequest.KeepAlive = true < font size = 2> ;


objWebRequest .Method =" POST";


MemoryStream postData = new MemoryStream();



StreamWriter sw = new StreamWriter(postData);


fso = new Scripting.FileSystemObjectClass();


sw.Write(encryptHeader(" func"," ll"));


sw.Write(encryptHeader(" objType",&q) uot; 144"));


sw.Write(encryptHeader(" objAction"," create2" ;));


sw.Write(encryptHeader("parentId","20553784")) ;


sw.Write(encryptHeader(" nextURL"," / teamepns-f / livelink。 exe?func = ll& objId = 5235138& objAction = browse& sort = name"));


sw.Write(encryptHeader(" name"," Some Document"));


sw。写(encryptHeader(" comment",""));


sw.Write(QUOT; - " + boundary + newLine);



UploadSpec objUpload = new UploadSpec(filePath," versionFile");


file.WriteLine(" Content-Disposition:form-data; name = \"" + objUpload.FieldName +" ; \" ;; filename = \"" +


objUpload.FileName +" \"" + newLine +" Content-Type:text / plain" + newLine);


sw.Write(" Content-Disposition:form-data; name = \" {0} \" ;; filename = \" {1} \" {2} Content-Type: application / octet-stream {2}",


objUpload.FieldName,


objUpload.FileName,


newLine);


postData.Write(objUpload.C​​ontents,0,objUpload.C​​ontents.Length);


string 内容= System.Text.ASCIIEncoding.ASCII.GetString(objUpload.C​​ontents);


file.WriteLine(contents );


sw.Write(encryptHeader(" InheritRequired"," 0"));


sw.Write(encryptHeader(" CREATE_Required"," 1"));



sw.Write(encryptHeader(" CREATE_Edited"," 0"));


sw.Write(encryptHeader(" CREATE_CacheID"," 0"));


sw.Write(encryptHeader(" CREATE_CatNames",""));


sw.Write(encryptHeader(" CTT_ID"," 20553784"));


sw.Write(encryptHeader(" CTT_PathSaved"," Upload Folder - Ameer));



sw.Write(encryptHeader(" CTT_Path"," Upload Folder - Ameer));


sw.Write(" ; - " + boundary +" - " + newLine);



using (Stream s = objWebRequest.GetRequestStream())


postData.WriteTo(s);



HttpWebResponse objResponse =(HttpWebResponse)objWebRequest.GetResponse();


Stream loginResponseStream = objResponse.GetResponseStream();


StringBuilder sb1 = new StringBuilder();


using (StreamReader reader =


new < font face ="Tahoma,Helvetica,Sans-Serif"> StreamReader(loginResponseStream,System.Text.Encoding.UTF8))


{


string line;


((line = reader.ReadLine())!= null


{


sb1。追加(行);


}


}


file.Close();


Console.WriteLine(sb1.ToString());



string output1 = sb1.ToString();


Console.WriteLine("\ nn \ nFile上传成功");


objResponse.Close();


sw.Close();


sw = null ;


objWebRequest = null ;


postData = null ;


objResponse = null < font size = 2> ;


}


请告诉我离开这个。


提前致谢


阿米尔

<二v class ="h2_lin">解决方案

嗨MohamedAmeer


我和你的问题完全相同。没有错误,但文件未上传。它在某个地方丢失了?


我一直在研究,谷歌搜索但没有灯光。如果你找到解决方案,请告诉我。谢谢堆....



Hi,

I am developing a class which uploads some files automatically to an application which accepts the file as input and upload. I am using HttpWebRequest object to send the request to the application.

Code is given below, but still it is not giving any error at the same time file is not uploaded to the server.

public static string Authenticate()

{

try

{

HttpWebRequest httpRequest =

(HttpWebRequest)WebRequest.Create(Constant.LiveLinkURL);

httpRequest.Method = "POST";

httpRequest.ContentType = "application/x-www-form-urlencoded";

string auth="func=ll.login&Username=" + Constant.UserID + "&Password=" + Constant.Password;

string next_url="/teamepns-f/livelink.exe?Redirect=1";

string currentTime = "D/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day +

":" + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second;

string login_url = auth + "&CurrrentClientTime=" + currentTime + "&nextURL=" + next_url;

byte[] bytedata = Encoding.UTF8.GetBytes(login_url);

httpRequest.ContentLength = bytedata.Length;

Stream requestStream = httpRequest.GetRequestStream();

requestStream.Write(bytedata, 0, bytedata.Length);

requestStream.Close();

 

HttpWebResponse httpWebResponse =

(HttpWebResponse)httpRequest.GetResponse();

Stream responseStream = httpWebResponse.GetResponseStream();

StringBuilder sb = new StringBuilder();

using (StreamReader reader =

new StreamReader(responseStream, System.Text.Encoding.UTF8))

{

string line;

while ((line = reader.ReadLine()) != null)

{

sb.Append(line);

}

}

int headerCount = httpWebResponse.Headers.Count;

string cookie="";

string server="";

string connection="";

for(int i=0;i<headerCount;i++)

{

if ( httpWebResponse.Headers.Keys.ToString() == "Set-Cookie" )

{

cookie = httpWebResponse.Headers + "; ";

}

else if ( httpWebResponse.Headers.Keys.ToString() == "Server" )

{

server = httpWebResponse.Headers;

}

else if ( httpWebResponse.Headers.Keys.ToString() == "Connection" )

{

connection = httpWebResponse.Headers;

}

}

char[] sep = {','};

string[] cookieValue = cookie.Split(sep);

string cookie1 = "LLInProgress=; ";

string llcookie="";

for(int i=0;i<cookieValue.Length;i++)

{

if ( cookieValue.StartsWith("LLCookie") )

{

llcookie = "LLCookie=" + cookieValue.Substring("LLCookie=".Length,cookieValue.IndexOf(";")-"LLCookie=".Length+2);

cookie1 += llcookie;

}

}

cookie1 += "LLTZCookie=0";

return cookie1;

}

catch(Exception exObj)

{

int index = exObj.Message.IndexOf("Unable to write data to the transport connection");

if ( exObj.Message.IndexOf("Unable to write data to the transport connection") >= 0 )

{

return "Error : Invalid URL - " + Constant.LiveLinkURL;

}

return "Error : " + exObj.Message;

}

}

public static void uploadFile()

{

cookie = Authenticate();  // get cookie from OS authentication

if ( cookie.StartsWith("Error : ") )

{

Console.WriteLine(cookie);

return;

}

boundary = Guid.NewGuid().ToString().Replace("-", "").Substring(0,15);

string nextURL="/teamepns-f/livelink.exe?Redirect=1";

HttpWebRequest objOSLoginWebRequest = (HttpWebRequest)WebRequest.Create("http://sww-knowledge-epe.shell.com/teamepns-f/livelink.exe?func=ll&objType=144&nextURL=" + nextURL + "&objAction=create&parentId=20553784");

objOSLoginWebRequest.ContentType="application/x-www-form-urlencoded";

objOSLoginWebRequest.Credentials=CredentialCache.DefaultCredentials;

objOSLoginWebRequest.Headers.Set("Cookie",cookie);

objOSLoginWebRequest.KeepAlive=true;

HttpWebResponse httpWebResponse =

(HttpWebResponse)objOSLoginWebRequest.GetResponse();

Stream responseStream = httpWebResponse.GetResponseStream();

StringBuilder sb = new StringBuilder();

using (StreamReader reader =

new StreamReader(responseStream, System.Text.Encoding.UTF8))

{

string line;

while ((line = reader.ReadLine()) != null)

{

sb.Append(line);

}

}

string filePath="C:\\Ameer\\PerfMon\\llperfmon-teamepns\\uploads\\TEST_DOC_001.txt";

objOSLoginWebRequest=null;

HttpWebRequest objWebRequest = (HttpWebRequest)WebRequest.Create("http://sww-knowledge-epe.shell.com/teamepns-f/livelink.exe");

objWebRequest.Headers.Set("Cookie",cookie);

objWebRequest.ContentType="multipart/form-data; boundary=" + boundary;

objWebRequest.Credentials=CredentialCache.DefaultCredentials;

objWebRequest.AllowWriteStreamBuffering=true;

objWebRequest.AllowAutoRedirect=true;

objWebRequest.KeepAlive=true;

objWebRequest.Method="POST";

MemoryStream postData = new MemoryStream();

StreamWriter sw = new StreamWriter(postData);

fso = new Scripting.FileSystemObjectClass();

sw.Write(encryptHeader("func","ll"));

sw.Write(encryptHeader("objType","144"));

sw.Write(encryptHeader("objAction","create2"));

sw.Write(encryptHeader("parentId","20553784"));

sw.Write(encryptHeader("nextURL","/teamepns-f/livelink.exe?func=ll&objId=5235138&objAction=browse&sort=name"));

sw.Write(encryptHeader("name","Some Document"));

sw.Write(encryptHeader("comment",""));

sw.Write("--" + boundary + newLine);

UploadSpec objUpload = new UploadSpec(filePath,"versionFile");

file.WriteLine("Content-Disposition: form-data; name=\"" + objUpload.FieldName + "\"; filename=\"" +

objUpload.FileName + "\"" + newLine + "Content-Type: text/plain" + newLine);

sw.Write("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}Content-Type: application/octet-stream{2}",

objUpload.FieldName,

objUpload.FileName,

newLine);

postData.Write(objUpload.Contents, 0, objUpload.Contents.Length);

string contents = System.Text.ASCIIEncoding.ASCII.GetString(objUpload.Contents);

file.WriteLine(contents);

sw.Write(encryptHeader("InheritRequired","0"));

sw.Write(encryptHeader("CREATE_Required","1"));

sw.Write(encryptHeader("CREATE_Edited","0"));

sw.Write(encryptHeader("CREATE_CacheID","0"));

sw.Write(encryptHeader("CREATE_CatNames",""));

sw.Write(encryptHeader("CTT_ID","20553784"));

sw.Write(encryptHeader("CTT_PathSaved","Upload Folder - Ameer"));

sw.Write(encryptHeader("CTT_Path","Upload Folder - Ameer"));

sw.Write("--" + boundary + "--" + newLine);

using (Stream s = objWebRequest.GetRequestStream())

postData.WriteTo(s);

HttpWebResponse objResponse = (HttpWebResponse)objWebRequest.GetResponse();

Stream loginResponseStream = objResponse.GetResponseStream();

StringBuilder sb1 = new StringBuilder();

using (StreamReader reader =

new StreamReader(loginResponseStream, System.Text.Encoding.UTF8))

{

string line;

while ((line = reader.ReadLine()) != null)

{

sb1.Append(line);

}

}

file.Close();

Console.WriteLine(sb1.ToString());

string output1 = sb1.ToString();

Console.WriteLine("\n\nFile uploaded sucessfully");

objResponse.Close();

sw.Close();

sw=null;

objWebRequest=null;

postData=null;

objResponse=null;

}

Please advise me to get out of this.

Thanks in Advance

Ameer

解决方案

Hi MohamedAmeer

I have exactly same problem as yours. No error but the file is not uploaded. it is lost somewhere?

I ve been researching, googling but no lights yet. If u find the solution could u please tell me. Thanks heaps....

 


这篇关于在C#中使用HttpWebRequest自动上传文件的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆