2012-05-16 64 views
3

我目前正在嘗試將我的Perl上傳腳本移植到C#,但我對該語言不太熟悉,無法使其工作。我試了很久,但似乎沒有任何工作。我感謝任何幫助。 :)如何將此Perl上傳腳本轉換爲C#?

Perl版本:

#!/usr/bin/perl -w 
use strict; 
use warnings; 
use LWP::Simple; 
use LWP::UserAgent; 
use HTTP::Request::Common; 
my ($user, $pass, $type, $fileName); 

# This chapter sets some vars and parses some vars. 
$/   = undef; 
$SIG{PIPE} = 'IGNORE'; 
$fileName = $ARGV[0] || die "Syntax: $0 <filename to upload> <free|prem|col> [login] [password]\n"; 
$type  = $ARGV[1] || ""; 
$user  = $ARGV[2] || ""; 
$pass  = $ARGV[3] || ""; 

# RapidShare API Documentation @ http://images.rapidshare.com/apidoc.txt 

my $nextuploadserver = get('http://rapidshare.com/cgi-bin/rsapi.cgi?sub=nextuploadserver'); 
die 'nextuploadserver broken' if $nextuploadserver !~ /^\d+$/; 
print 'nextuploadserver:' . $nextuploadserver . "\n"; 

my $userAgent = LWP::UserAgent->new(); 
my $request = POST 'http://rs' . $nextuploadserver . '.rapidshare.com/cgi-bin/rsapi.cgi', 
    Content_Type => 'form-data', 
    Content  => [ 
    sub   => 'upload', 
    login  => $user, 
    password => $pass, 
    filename => $fileName, 
    filecontent => [$fileName], 
    ]; 
my $response = $userAgent->request($request); 
die 'fucked up' if $response->is_error(); 
print $response->content . "\n"; 

C#,這是我曾嘗試:

WebClient wc = new WebClient(); 
wc.Headers["Content-Type"] = "form-data"; 
System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(); 
string a = utf8.GetString(
wc.UploadData(
@"https://rs702l3.rapidshare.com/ 
cgi-bin/rsapi.cgi", "POST", System.Text.Encoding.UTF8.GetBytes(
"sub=upload&login=XXXX&password=XXXX&folder=0&filename=Test.jpg 
&filecontent=" + utf8.GetString(File.ReadAllBytes(@"D:\Test.jpg"))))); 

Console.WriteLine("Test: " + a); 

PS:如果有人正在尋找這是工作的一個免費電子uplaod腳本,你可以自由地使用我的,因爲我發佈在線程中。 :)

+0

什麼是不工作?你會得到一個例外或隨機字符或? –

回答

1

下面是我們使用一些C#郵編:

string uri = "http://..."; 
string parameters = String.Format("param1={0}&param2={1}", 
            HttpUtility.UrlEncode(param1), 
            HttpUtility.UrlEncode(param2)); 

HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(uri); 
webRequest.ContentType = "application/x-www-form-urlencoded"; 
webRequest.Method = "POST"; 
webRequest.AllowAutoRedirect = true; 
webRequest.MaximumAutomaticRedirections = 1; 

byte[] bytes = Encoding.ASCII.GetBytes(parameters); 
Stream os = null; 
try { 
    webRequest.ContentLength = bytes.Length; 
    os = webRequest.GetRequestStream(); 
    os.Write(bytes, 0, bytes.Length); 
} catch (Exception ex) { 
    // Handle exception 
} finally { 
    if (os != null) { 
     os.Close(); 
    } 
}