Upload to PHP server from c sharp client application - c#

Currently i have a c sharp application (Client app). and a web application written php. I want to transfer some files whenever a particular action is performed at client side. Here is the client code to upload the file to php server..
private void button1_Click(object sender, EventArgs e)
{
System.Net.WebClient Client = new System.Net.WebClient();
Client.Headers.Add("Content-Type", "binary/octet-stream");
byte[] result = Client.UploadFile("http://localhost/project1/upload.php", "POST",
#"C:\test\a.jpg");
string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
}
Here is the upload.php file to move the file..
$uploads_dir = './files/'; //Directory to save the file that comes from client application.
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
I'm not getting any errors from above code. but it does not seem to be working. Why is it? Am i missing something?

Your current PHP code is for handling multiple file uploads, but your C# code is only uploading one file.
You need to modify your PHP code somewhat, removing the foreach loop:
<?php
$uploads_dir = './files'; //Directory to save the file that comes from client application.
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
?>
You also need to ensure that the ./files directory exists.
I have tested the above PHP code with your C# code and it worked perfectly.
For more information on handling file uploads, refer to the PHP documentation.
For more information on uploading multiple files with C# and PHP, here are some helpful links:
Upload files with HTTPWebrequest (multipart/form-data)
Use Arrays in HTML Form Variables
PHP: Uploading multiple files
If you want something simple for uploading multiple files, you just just upload one file at a time to upload.php in a C# loop.

Your php code seems right, however you try to access the file using the "picture" key of the $_FILES global. It does not seems to be specified in your csharp code. I don't know how to do it thought. You could try to see how it was named in your php by doing a print_r or vardump of you $_FILE global or using the array_keys function
Regards
Edit: I found this link that could help you to add a "name" to your uploaded file:
http://www.bratched.com/en/home/dotnet/69-uploading-multiple-files-with-c.html

Related

C# WebClient can not upload large files

I have a large file (500MB) and my application can not send it to my webpage.
public static void UploadFile(string url, string fileName) {
WebClient client = new WebClient();
byte[] responseBinary = client.UploadFile(url, fileName);
string response = Encoding.UTF8.GetString(responseBinary);
MessageBox.Show(response);
}
It sends to a php file. I tried a check
var_dump($_FILES);
var_dump($_REQUEST);
but both of them is empty.
When I try to upload a small file (8KB) it is in $_FILES['file'].
What am I doing wrong?
You have to modify your server's php.ini file to allow big files to be sent to it, those are the two directives you have to modify:
upload_max_filesize = 900M
post_max_size = 900M
Also, remember to restart apache or nginx or whatever is your server after you edited the php.ini file.
EDIT
If you don't have access to this kind of configuration on your host, you could try (it may, or may not be allowed) modifing this settings at .htaccess file (on the root of your site) adding the following to it:
php_value upload_max_filesize 900M
php_value post_max_size 900M

Send txt file through URL with c# & PHP?

So basically I've been trying to figure a way to send a text file i receive from a users computer, (Im doing this to allow users to upload certain text files to my website, kinda like storage(i know it sounds kinda stupid)) then once its retrieved i will send the data (from the text file) to my website using the following code:
private void Form1_Load(object sender, EventArgs e)
{
string userDocPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string Path_ = Path.Combine(userDocPath, "RevTech", "Source", "Custom.txt");
WebClient wc = new WebClient();
string txt = File.ReadAllText(Path_);
wc.DownloadString("https://example.com/k/gettext.php?source="+txt);
}
Once that is called i have a page hosted on my server that uses PHP to $_GET['source'] then i use this and use
$myfile = fopen("test.txt", "w") or die("Unable to open file!");
fwrite($myfile, $_GET['source']);
fclose($myfile);
Then when i check to see if the text file was successfully added to my server it doesn't correctly? Hopefully you all understand my question, if you did do any of you possibly have a solution to it? By the way sorry for my bad English

Using webclient to download images from deployed website

i deployed a website on IIS running on localhost/xxx/xxx.aspx . On my WPF side , i download a textfile using webclient from the localhost server and save it at my wpf app folder
this is how i do it :
protected void DownloadData(string strFileUrlToDownload)
{
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
MemoryStream storeStream = new MemoryStream();
storeStream.SetLength(myDataBuffer.Length);
storeStream.Write(myDataBuffer, 0 , (int)storeStream.Length);
storeStream.Flush();
string currentpath = System.IO.Directory.GetCurrentDirectory() + #"\Folder";
using (FileStream file = new FileStream(currentpath, FileMode.Create, System.IO.FileAccess.ReadWrite))
{
byte[] bytes = new byte[storeStream.Length];
storeStream.Read(bytes, 0, (int)storeStream.Length);
file.Write(myDataBuffer, 0, (int)storeStream.Length);
storeStream.Close();
}
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
}
This is by writing btyes and saving them . But how do i download multiple image files and save it on my WPF app folder? I have a URL like this localhost/websitename/folder/designs/ , under this URL , there is many images , how do i download all of them ? and save it on WPF app folder?
Basically i want to download the contents of the folder whereby the contents are actually images.
First, the WebClient class already has a method for this. Use something like client.DownloadFile(remoteUrl, localFilePath).
See this link:
WebClient.DownloadFile Method (String, String)
Secondly, you will need to index the files you want to download on the server somehow. You can't just get a directory listing over HTTP and then loop through it. The web server will need to be configured to enable directory listing, or you will need a page to generate a directory listing. Then you will need to download the results of that page as a string using WebClient.DownloadString and parse it. A simple solution would be an aspx page that outputs a plaintext list of files in the directory you want to download.
Finally, in the code you posted you're saving every single file you download as a file named "Folder". You need to generate a unique filename for each file you want to download. When you're looping through the files you want to download, use something like:
string localFilePath = Path.Combine("MyDownloadFolder", imageName);
where imageName is a unique filename (with file extension) for that file.

Sending file(s) to my PHP script via C#

I have been working on my first C# application lately and I finished working on the interface - it's perfect.
Now I am stuck at the part where I get an Open File dialog and then send that file to my PHP script located on localhost (wamp).
This is what I've been trying to do:
private void menu_upload_file_Click(object sender, EventArgs e)
{
DialogResult dialogOpened = openFileDialog1.ShowDialog();
if (dialogOpened == DialogResult.OK)
{
string filename = openFileDialog1.FileName;
using (var client = new WebClient())
{
client.UploadFile("http://dugi/imgitv3/upload.php?submit=true&action=upload", "POST", filename);
}
}
}
Nothing is happening and the file is not being sent (copied over) to my desired location.
You might understand that I am succeeding on opening the Open File dialog, but I have no clue if I am catching the filename/directory and send it over to my website so it can deal with it.
Maybe the url is complicated? I need to send those submit and action parameters or the script wont load.
OH AND: In PHP, the $_FILES array MUST BE named images ($_FILES['images']), maybe this is the problem? (thought of this while asking here).
So what is the problem that the file is not being sent to my website?
Assuming the client.UploadFile("http://dugi/imgitv3/upload.php?submit=true&action=upload", "POST", filename); is not throwing an exception try to look at the response.
var response = client.UploadFile("http://dugi/imgitv3/upload.php?submit=true&action=upload", "POST", filename);
Console.WriteLine("\nResponse Received.The contents of the file uploaded are:\n{0}",
System.Text.Encoding.ASCII.GetString(response));
The problem was in my PHP script. I was always looking for $_FILES['images'] there and nothing else. Then after some googles, I noticed that C# sends the file array named with file ($_FILES['file']).
I did the necessary changes in my PHP script and now everything is working.

c# write to text file on website trough php

Within c#, i can put data to seperate strings.
For example the current date i put to a string called line1 and some info i put to a string called line2.
What i want to do now, is sent these 2 strings to a web adress that handles these lines, and write them into a simple text file. (or can i write to a text file on a website directly from C# ?)
My knowlage of php is very low, but so far i found this code to be working:
<?php
$File = "name.txt";
$Handle = fopen($File, 'a');
$Data = "line1\n";
fwrite($Handle, $Data);
$Data = "line2\n";
fwrite($Handle, $Data);
print "Data Added";
fclose($Handle);
?>
The C# application is running on a computer, not the website (WPF window).
But now it only has the content of the $Data written to the "name.txt" file.
Does anyone know how i could link the text that is binded to the stings in C3, to the datafields defined in the PHP, so that the text from the strings gets written to the text file on the website? Or would it be possible to write directly to a text file without the php in between ?
So, you have a C# app that you want to use to send 2 bits of data to a PHP based website, and have the website write the data into a file? If that's what you want, you'll need to do something like the following...
On the website, create a receiving PHP file. The bones of it would be something like :
<?php
$File = "name.txt";
$Handle = fopen($File, 'a');
$line1 = $_GET["line1"] . "\n";
fwrite($Handle, $line1);
$line2 = $_GET["line2"];
fwrite($Handle, $line2);
print "Data Added";
fclose($Handle);
echo "Completed writing data to the file";
?>
and to submit that data from the C# app to the website, do something as simple as
WebClient wc = new WebClient();
Console.WriteLine(wc.DownloadString("http://example.com/Receiver.php?line1=this is the first line&line2=and this is the second"));
(
NOTE : No error handling is included in this code, and anyone who knows the URL for the receiver will be able to overwrite your file with whatever they like. Take care when actually implementing this.
ALSO NOTE : It is years since I did much with PHP, so you will probably need to tweak the code.
AND ANOTHER THING : the WebClient.DownloadString approach is as basic as it gets. You may want to look at HttpWebRequests if you need more control
)
You can write to a text file on a website directly from C#.
System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath("/file.txt"););
file.WriteLine("First line.");
file.WriteLine("Secondline.");
file.Close();
It will create a file in the root of your website (the user running the site has to have write permissions in this directory)

Categories