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)
Related
My program generates a script for another application. How can I also make opening this script in that application? And is it possibly to be done without using an external file? My program is written in Xamarin and C# (due to use of one C# library), but obviously any Objective-C solution is appropriate.
I found that the only way is to write information to a file and to open this file programmatically with another application. Class NSWorkspace helps to do that:
NSString *data = #"Some data";
NSString *filename = #"Some filename";
[data writeToFile:path
atomically:NO
encoding:NSUTF8StringEncoding
error:nil];
[[NSWorkspace sharedWorkspace] openFile:filename
withApplication:#"Graphviz"];
And the code for C#:
using AppKit;
using System.IO;
...
string data = "Some data";
string filename = "Some filename";
File.WriteAllText (filename, data);
NSWorkspace.SharedWorkspace.OpenFile (filename, "Graphviz");
Probably, to do that without using files external application must support AppleScript, but it doesn't.
In my application I'm saving an image and transferring to a server through the use of a php script whose sole job is to pass this image to the server which saves it in the root of the server.
The code I have for my upload is as follows:
NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "TTR");
nvc.Add("btn-submit-photo", "Upload");
UploadToServer.HttpUploadFile(Settings.Default.ServerAddress , sfd.FileName.ToString(), "file", "image/jpeg", nvc);
Settings.Default.ServerAddress holds the location of my upload php script which the following:
http://server.foo.com/images/upload.php
I have another php script that returns a string of all the file and folders held on my server that is returned and displayed in a text box.
I'm calling this like so:
using (var client = new WebClient())
{
result = client.DownloadString("http://server.foo.com/images/getDirectoryList.php");
}
What I need to do is have a way so that I can choose the location of where the my image is stored. My feeling is telling that I need to do is have a way so that when a user selects anything with .folder, the old string list disappears and the images and files is stored within that folder.
I believe the call I need to make is something like this:
http://server.foo.com/images/getDirectoyList.php?dir=test_folder
But I'm stuck on trying to implement what I want. For one, the list I get back is all highlight and say I get something like
Image 1
Image 2
Test_folder.folder
I have no way of being able to simply click on Image 2 and have it highlight the whole thing. Instead is simply places the cursor where I clicked. Likewise I have no idea of how I would pass this information over to the my upload code so that my chosen directory is used to store the image as opposed to the root.
Has anyone ever attempted something like this before?
Do you have any links or advice that could help me achieve what it is I want to achieve?
Additionally, but not important, would I be able to ever create a new directory / folder on my server through my C# winform application without having to touch either the php scripts or the server itself?
I have a unity C# program which is uploading a binary file (with some data).
(which is kind of irrelvant but maybe not)
var form = new WWWForm();
form.AddField("docid", "A");
byte[] textarr = Encoding.ASCII.GetBytes("just a sample text to be compressed and sent to server");
form.AddBinaryData("file", textarr,"file.tmp");
string req = "my url";
WWW www = new WWW(req,form);
I want to take the file content (as binary) so that I will be able to send into the database as binari in the PHP side.
I am trying to do something like this:
$binaridata = ~$_FILES["file"]["name"] (what do i need to do here? tried
file_get_content etc, but it always yield some errors)
Thanks for your help!
$binaryData = file_get_contents($_FILES['file']['tmp_name']);
^^^^^^^^
The file is stored at the path indicated by tmp_name, name is just the name given by the client and practically irrelevant.
Depending on how you talk to the database and what database, you don't want to read the entire file contents into a variable though. For instance, using Postgres via PDO, you'd do this:
$stmt = $pdo->prepare('INSERT INTO ... VALUES (:file)');
$fh = fopen($_FILES['file']['tmp_name'], 'rb');
$stmt->bindParam(':file', $fh, PDO::PARAM_LOB);
$stmt->execute();
The database adapter will read the file as a stream, which is much more economic than saving it in memory. Consult your database adapter's manual.
why not try
$binaridata = $_FILES["file"]["name"];
add the semicolon and remove the ~
Shadowpat
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
I have the following C# code to produce a small PHP file. The reason I am doing this is to update 400 plus sites automatically. The sites are in PHP on a Windows Environment so using C# for utility apps is the easiest for me.
fileContents.AppendFormat("<?php{0}",Environment.NewLine);
fileContents.AppendFormat("# FileName=\"clientsite.php\"{0}",Environment.NewLine);
fileContents.AppendFormat("# HTTP=\"true\"{0}",Environment.NewLine);
fileContents.AppendFormat("$clientname = \"{0}\";{1}", clientsiteName, Environment.NewLine);
fileContents.AppendFormat("$version = \"v6.2i\";{0}",Environment.NewLine);
fileContents.Append("?>");
The end result of this file causes a strange character to appear on the PHP page that includes this page. When I manually open the created PHP file - press backspace on the last line then enter it works. Is there something better than Environment.NewLine to use for this? Or is there another problem I am missing?
EDIT: The character looks like something I can't reproduce on the keyboard (squiggle line) by ends with ?
You could just try "\n", I believe Environment.NewLine is "\r\n".
But it could also be about how you write the StringBuilder (I assume fileContents is a StringBuilder) to the file. If you e.g. use WriteAllText, you could try using different encoding.