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
Related
I am relatively new to C#/Visual Studio 2015 application development, coming from Android. I am writing a chat application that also allows users to send files to each other. The file transfer functionality is in place; the file gets downloaded to a pre-set folder when received, and the file-path of that file is then shown in the chat box to the recipient. However, that file path is shown as though it were regular text.
How do I make it such that said file-path (and/or urls, ideally) appear as a clickable hyperlinks, that then open said file?
Any help or resources to be pointed to would be most appreciated!
If you create a linkLabel object to show the path, you can add a callback to the event LinkClicked and open a file explorer:
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("C:/");
}
Here we go:
You should use Uri class to build your url from string:
string filePath = "C:\\example.txt";
Uri uri = new Uri(filePath);
return uri.AbsoluteUri;
Hope it helps;)
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.
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.
I need to download an encrypted xml binary file from a url which has been encrypted using JAVA. I have managed to encrypt the file in JAVA, then add the file in my WP7 project and decrypt using c# and read the file into my app succesfully.
I need to now store the file on a web server so the app can access it and I'm finding that the file is not complete or in the incorrect format when I download it and the decryption does not work.
I have tried using both WebClient and HttpWebRequest and both give me the same result. The xml encoded file is approximately 17000 bytes but the file downloaded from both of these methods return a file about 16000 bytes long. I think the downloaded file is missing end of line characters but I can't verify this. The code I'm using at the moment to download the file is pretty simple and is as follows:
private void GetFile()
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
String url = "http://url/encodedfile.txt";
client.DownloadStringAsync(new Uri(url));
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string s = e.Result;
byte[] encodedFile = System.Text.Encoding.UTF8.GetBytes(e.result);
//decrypt file....
Looking at the encrypted data they look very similar but the length of encodedFile is not the correct length of the original encrypted file.I've debugged this and copied the characters in encodedFile to TextPad its all on one line. I'm not sure if that's the issue or not but I've looked everywhere on how to download a binary file and most suggestions are to use HttpWebRequest but I get the exact same result so I don't think that is the issue.
Any help appreaciated.
DownloadString will try to read the data as an unicode string. Since you're downloading binary data, it's no wonder the output isn't correct. Try using WebClient.OpenReadAsync instead:
private void GetFile()
{
var webClient = new WebClient();
webClient.OpenReadCompleted += OpenReadCompleted;
string url = "http://url/encodedfile.txt";
webClient.OpenReadAsync(new Uri(url));
}
private void OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
// Decrypt the contents of e.Result
}
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