Sending file(s) to my PHP script via C# - 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.

Related

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

Get full file path including file's name from an uploaded file in C#

I have this web application project which requires a better user-interface and I am doing it by C#.
I already have my html file with JS done but I need some data from user.
In my JS embedded in HTML file, I used the code below to find the file on local driver and get the data from that excel file and then put all these data into an array.
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open(file1);
var excel_sheet = excel.Worksheets("Sheet1");
However, the "file1" you see above seems to require a full name path,say "C:\test.xls" in my case.
I am new to C# and just built a button on my form design, by clicking the button, I seem to be able to browse my local file.
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
System.Diagnostics.Process.Start(file);
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
So, my question:
How can I get this kind of full file path of an uploaded file in C# ?
And furthermore, it would be awesome if some one can tell me how to get this value into my javascript or HTML!
Thank you in advance
You won't be able to depend on getting the full path. In the end, the browser only needs to multi-part encode the physical file and submit it as a form post (of sorts). So once it has it's location and has encoded it -- it's done using it.
It's considered a security risk to expose the file structure to Javascript/HTML (ie., the internet).
Just an update.
I used another logic and it worked as expected. Instead of getting absolute file path , I managed to open the file , save it as somewhere and make my html call find that file path no matter what.

How to download and upload file to SkyDrive via Live Connect SDK

I have an app that I want to download & upload a simple .txt file with a URL inside. I have downloaded Live Connect SDK V5.4, referenced the documentation, but it appears that the documentation is incorrect. The sample code uses event handlers for when a download/upload is complete, but that no longer can be used in V5.4.
I have two methods, downURL & upURL. I have started working on downURL:
private async void downURL()
{
try
{
LiveDownloadOperationResult download = await client.DownloadAsync("URL.txt");
}
catch { }
}
I am not sure what I am suppose to use for the path, I put "URL.txt" for now, I've seen some examples with "/me/". Do I need this? The file does not need to be visible to the user, as the user can't really do anything with it, but it is vital for the app to work.
My question is how do I use the LiveDownloadOperationResult download to save the file to Isolated Storage Settings, get the text contents, and put that in a string? Also, if you know how to upload the file back up, the upload event handler looks the same (but without the Result variable).
This code help you download content a file which you want. It get content have format OpenXML
Here, "item.id" is Id of "URL.txt".
private async void downURL()
{
try
{
LiveDownloadOperationResult operationResult = await client.DownloadAsync(item.id + "/Content?type=notebook");
StreamReader reader = new StreamReader(operationResult.Stream);
string Content = await reader.ReadToEndAsync();
}
catch { }
}

Upload to PHP server from c sharp client application

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

User Permissions issue

I am using Visual Studio C# to parse an XML document for a file location from a local search tool I am using. Specifically I am using c# to query if the user has access to certain files and hide those to which it does not have access. I seem to have files that should return access is true however because not all files are local (IE some are web files without proper names) it is not showing access to files it should be showing access to. The error right now is caused by a url using .aspx?i=573, is there a work around or am I going to have to just remove all of these files... =/
Edit: More info...
I am using right now....
foreach (XmlNode xn in nodeList)
{
string url = xn.InnerText;
//Label1.Text = url;
try
{ using (FileStream fs = File.OpenRead(url)) { }
}
catch { i++; Label2.Text = i.ToString(); Label1.Text = url; }
}
The issue is, when it attempts to open files like the ....aspx?i=573 it puts them in the catch stack. If I attempt to open the file however the file opens just fine. (IE I have read access but because of either the file type or the append of the '?=' in the file name it tosses it into the unreadable stack.
I want everything that is readable either via url or local access to display else it will catch the error files for me.
I'm not sure exactly what you are trying to do, but if you only want the path of a URI, you can easily drop the query string portion like this:
Uri baseUri = new Uri("http://www.domain.com/");
Uri myUri = new Uri(baseUri, "home/default.aspx?i=573");
Console.WriteLine(myUri.AbsolutePath); // ie "home/default.aspx"
You cannot have ? in file names in Windows, but they are valid in URIs (that is why IE can open it, but Windows cannot).
Alternatively, you could just replace the '?' with some other character if you are converting a URL to a filename.
In fact thinking about it now, you could just check to see if your "document" was a URI or not, and if it isn't then try to open the file on the file system. Sounds like you are trying to open any and everything that is supplied, but it wouldn't hurt to performs some checks on the data.
private static bool IsLocalPath(string p)
{
return new Uri(p).IsFile;
}
This is from Check if the path input is URL or Local File it looks like exactly what you are looking for.
FileStream reads and writes local files. "?" is not valid character for local file name.
It looks like you want to open local and remote files. If it is what you are trying to do you should use approapriate metod of downloading for each type - i.e. for HTTP you WebRequest or related classes.
Note: it would be much easier to answer if you'd say: when url is "..." File.OpenRead(url) failes with exception, mesasge "...".

Categories