Here is my C# code:
WebClient myClient = new WebClient();
NameValueCollection inputs = new NameValueCollection();
inputs.Add("decrement", "true");
System.Uri uri = new System.Uri ("http://myserver/myPHP.php");
myClient.UploadValuesAsync (uri, "POST", inputs);
Here is my myPHP.php file on the server:
if($_POST['decrement'] == "true") {
$file = './myTextFile.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
}
The txt file is not being written to, why not?
NOTE: myPHP.php and myTextFile.txt are in the same directory on the server
If your file is directly under htdocs:
$file = $_SERVER['DOCUMENT_ROOT'] . '/myTextFile.txt';
Related
I have build an API which gives output in zip file when more than one file is requested
Now I have to download this zip file in C# WPF app.
To access API, we have to use POST ( instead of GET ) and JSON parameters.
I am able to download one file as string with help of below code
WebClient client = new WebClient();
var vm = new { from = "A", to = "S", files= "all", type = "csv", file = "Single" };
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var dataString = JsonConvert.SerializeObject(vm);
var response = client.UploadData("https://myurl.com/data", "POST", System.Text.Encoding.ASCII.GetBytes(dataString));
But not able to figure out how to download zip file and save it to disk
Helo, i already search on Google and here (StackOverflow) but no any solution i complete.
I Have a Excel file in my folder and i need to create a method on my controller to download this file.
And in my React Web Site i need to get this file to user computer.
I try to use ActionResult, FileStreamResult, HttpResponseMessage and other, read file from folder with File.ReadAllbytes, put the Header on response.
On the final i get this.
{ FileContents: "allcontentoffilehere....", Contenttype: "application/octet-stream", FileDownloadName: "filename.xls"}
And using this JavaScript do download:
var bytes = new Uint8Array(responseDownloadFile.data.FileContents);
var blob = new Blob([bytes], {
type: responseDownloadFile.data.ContentType
});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = responseDownloadFile.data.FileDownloadName;
document.body.appendChild(link);
link.click();
But the file when download is corrupted.
Any on can help me?
Try to return HttpResponseMessage type on your API
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent([file bytes]);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/file type");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "filename.xlsx"
};
return result;
And on your Front end execute code:
window.location.href = "link to your api endpoint to download excel";
I am trying to make for example a simple weather app. Mine is for an Air Quality API.
I had this code but I didn't think it would work with JSON.
var webClient = new WebClient();
...
var text = e.Result; // get the downloaded text and store in this variable
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = "downloaded.txt"; // local file to save text in
string localPath = Path.Combine(documentsPath, localFilename); // local path to save file to
File.WriteAllText(localPath, text); // writes to local storage
myTextView.Text = text; // updates the TextView element on the screen with downloaded text data
Then Just
var url = new Uri("https://api.breezometer.com/baqi/?lat=" + latitude + "&lon=" + longitude +"&key=YOUR KEY HERE");
webClient.Encoding = Encoding.UTF8;
webClient.DownloadStringAsync(url);
Im just not sure of the encoding method for JSON.
If anyone knows please answer thanks...
Use the WebClient class in System.Net:
var json = new WebClient().DownloadString("url");
Origin answer:
How to get a json string from url?
I am uploading a file with C# code on php server. But facing some issues.
First I was using a WebClient Object to upload file by calling UploadFile() method, and uploading string to by calling UploadString() method by following code:
String StoreID = "First Store";
WebClient Client = new WebClient();
String s = Client.UploadString("http://localhost/upload.php", "POST", StoreID);
Client.Headers.Add("Content-Type","binary/octet-stream");
byte[] result = Client.UploadFile("http://localhost/upload.php", "POST", "C:\\aaaa.jpg");
s = s + System.Text.Encoding.UTF8.GetString(result,0,result.Length);
Issue is that I am requesting two times so string and file is not being send at same time. I am receiving either String or File. But I need both at same time. I don't want to use UploadData() becuase it will use byte codes and I have know I idea how to extract it in php.
Let that string is folder name, i have to send string and file, so that file could save at specified folder at php server.
I studied there may be a solution with WebRequest and WebResponse object. But dont know how to send request using WebResponse by C# and get it at PHP.
Any Suggestions!!!!
Try this :
WebClient web = new WebClient();
try{
web.UploadFile("http://" + ip + "/test.php", StoreID);
}
catch(Exception e)
{
MessageBox.Show("Upload failed");
}
Now you can access the file from the PHP file.
<?php
//check whether the folder the exists
if(!(file_exists('C:/Users/dhanu-sdu/Desktop/test')))
{
//create the folder
mkdir('C:/Users/ComputerName/Desktop/test');
//give permission to the folder
chmod('C:/Users/ComputerName/Desktop/test', 0777);
}
//check whether the file exists
if (file_exists('C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
//move the file into the new folder
move_uploaded_file($_FILES["file"]["tmp_name"],'C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]);
}
?>
Also, you can download data from a PHP server and display it in a C# web browser by using the following codes :
WebClient web = new WebClient();
try{
byte[] response = web.DownloadData("http://" + ip +"/test.php");
webBrowser1.DocumentText = System.Text.ASCIIEncoding.ASCII.GetString(response);
}
catch(Exception e)
{
MessageBox.Show("Download failed");
}
You can create a webservice with php that accepts a file. Then publish that webservice, and add it to you c# references, then just call teh method from within your c# code that accepts the file, and vualá!
How to create SOAP with php link
I have a File.aspx form where I display all the files.
When I upload a file I am using a upload.aspx file to run c# code to upload the file.
The thing is that at the end , I want to refresh the page automatically to display the new file upload but apparently it's not redirecting even if all the parameters are good.
This is the code I use
HttpContext postedContext = HttpContext.Current;
string param = Request.UrlReferrer.Query;
string param2 = Request.UrlReferrer.Query;
var url = HttpUtility.ParseQueryString(param).Get("projectName");
var url2 = HttpUtility.ParseQueryString(param2).Get("projectId");
HttpPostedFile file = postedContext.Request.Files[0];
string name = file.FileName;
byte[] binaryWriteArray = new
byte[file.InputStream.Length];
file.InputStream.Read(binaryWriteArray, 0,
(int)file.InputStream.Length);
//FileStream objfilestream = new FileStream(Server.MapPath("~\\" + "\\Files\\" + url + "\\" + name), FileMode.Create, FileAccess.ReadWrite);
FileStream objfilestream = new FileStream(("C:\\inetpub\\wwwroot\\Clientportal\\Files\\" + url + "\\" + name), FileMode.Create, FileAccess.ReadWrite);
objfilestream.Write(binaryWriteArray, 0, binaryWriteArray.Length);
objfilestream.Close();
string[][] JaggedArray = new string[1][];
JaggedArray[0] = new string[] { "File was uploaded successfully" };
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(JaggedArray);
Response.Write(strJSON);
Response.Redirect(string.Format("Files.aspx?projectId={0}&projectName={1}", url2, url));
Any ideas ? I'm a bit stuck because I use this response.redirect everywhere and it works only when the code is in the same code file...
Maybe it's because of the fact that I try to redirect from another code file ?
I would attempt to do reload on client side by using javascript:
window.location.reload()
if the JSON you get as a response contains message "File was uploaded successfully"
If you are not using ajax for submitting the file you don't need to write json. It's enough to redirect to the suitable url that contains a parameter that identifies status of file upload operation.