I am using this code:
using System.Net;
function() {
using (WebClient Client = new WebClient())
{
Client.DownloadFile("http://translate.google.com/translate_tts?tl=en&q=hello", "a.mp3");
}
}
Its working fine. Notice please the English language I am downloading. The main problem comes when I'd like to do the same with language using non-latin letter, for example Thai:
using System.Net;
function() {
using (WebClient Client = new WebClient())
{
Client.DownloadFile("http://translate.google.com/translate_tts?tl=th&q=สวัสดี", "a.mp3");
}
}
But this is giving me such a nonsence mp3 without that word sound. How to fix it please?
Notice the main structure of this website:
...translate.google.com/translate_tts?tl=**en**&q=**hello**"
...translate.google.com/translate_tts?tl=**th**&q=**สวัสดี**"
Use HttpUtility.UrlPathEncode("สวัสดี") to encode the Unicode characters.
Related
I am trying to download HTML webpage locally to my computer and this works fine, however, it is a Bulgarian article and it does not seem to display properly afterwards.
I have tried many encoding (Code Page Identifiers - WINDOWS-1251, UTF-8, etc.) from MSDN https://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx but for some reason I cannot get it to open as intended.
For example:
Стара планина - величествената кръстница на Балканския полуостров
Displays as:
??N�?�N�?� ???�?�???????� - ???�?�??N�?�N?N�???�???�N�?� ??N�NSN?N�????N�?� ???� ?�?�?�???�??N?????N? ?????�N???N?N�N�????
Below I am posting my simple code. Your help will be much appreciated! :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace pageDownloader
{
class Program
{
public static void DownloadPage()
{
WebClient client = new WebClient();
string webpage = client.DownloadString("http://www.nasamnatam.com/statia/Stara_planina_velichestvenata_krystnica_na_Balkanskiia_poluostrov-2525.html");
System.IO.File.WriteAllText(#"C:\test\downloadedpage.html", webpage, Encoding.GetEncoding("windows-1251"));
}
static void Main()
{
DownloadPage();
}
}
}
Console.OutputEncoding = Encoding.UTF8;
string htmlCode = "";
WebClient client = new WebClient { Encoding = Encoding.UTF8 };
byte[] reply = client.DownloadData($"http://www.nasamnatam.com/statia/Stara_planina_velichestvenata_krystnica_na_Balkanskiia_poluostrov-2525.html");
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding encoding1251 = Encoding.GetEncoding("windows-1251");
var convertedBytes = Encoding.Convert(encoding1251, Encoding.UTF8, reply);
htmlCode = Encoding.UTF8.GetString(convertedBytes);
I am using a C# WinForms app to scrape some data from a webpage that uses charset ISO-8859-1. It works well for many special characters, but not all.
(* Below I use colons instead of semi-colons so that you will see the code that I see, and not the value of it)
I looked at the Page Source and I noticed that for the ones that won't display correctly, the actual code (e.g. ū:) is in the Page Source, instead of the value. For example, in the Page Source I see Ryū: Murakami, but I expect to see Ryū Murakami. Also, there are many other codes that appear as codes, such as Ş: ō: š: č: ă: ș: and many more.
I have tried using WebClient.DownloadString and WebClient.DownloadData.
Try #1 Code:
using (WebClient wc = new WebClient())
{
wc.Encoding = Encoding.GetEncoding("ISO-8859-1");
string WebPageText = wc.DownloadString("http://www.[removed].htm");
// Scrape WebPageText here
}
Try #2 Code:
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
using (WebClient wc = new WebClient())
{
wc.Encoding = iso;
byte[] AllData = wc.DownloadData("http://www.[removed].htm");
byte[] utfBytes = Encoding.Convert(iso, utf8, AllData);
string WebPageText = utf8.GetString(utfBytes);
// Scrape WebPageText here
}
I want to keep the special characters, so please don't suggest any RemoveDiacritics examples. Am I missing something?
Consider Decoding your HTML input.
iam working on unity3d project. i need set of files to be downloaded from the server. iam using C# for scripting. after a hour of google i haven't found a solution because of poor documentation. can anyone give me example code for download file from url and save it in a specific location in unity3d?
Unity3D uses the implementation of C# known as Mono. Mono supports almost everything available in the standard .NET library. Thus, whenever you are wondering 'How do I do that in Unity?', you can always take a look at the documentation for .NET available at msdn.com which is by no way poor. Regarding your question, use the WebClient class:
using System;
using System.Net;
using System.IO;
public class Test
{
public static void Main (string[] args)
{
WebClient client = new WebClient();
Stream data = client.OpenRead(#"http://google.com");
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
Console.WriteLine(s);
data.Close();
reader.Close();
}
}
Edit
When downloading an image file, use the DownloadFile method provided by WebClient:
WebClient client = new WebClient();
client.DownloadFile("http://upload.wikimedia.org/wikipedia/commons/5/51/Google.png", #"C:\Images\GoogleLogo.png")
Take a look at the WWW functions in Unity 3d.
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
IEnumerator Start() {
WWW www = new WWW(url);
yield return www;
renderer.material.mainTexture = www.texture;
}
}
Asset bundles if you are looking to compress your data packets.
var www = new WWW ("http://myserver/myBundle.unity3d");
yield www;
// Get the designated main asset and instantiate it.
Instantiate(www.assetBundle.mainAsset);
Note that some functions are only Ready only... like the www.url function. Some of the examples have been moved to the Manual section instead of the scripting section as well.
Hope this helps.
-Mark
You can use System.Net.WebClient to download file asynchronously.
something like
System.Net.WebClient client = new WebClient();
client.DownloadFileAsync(new Uri("your uri"), "save path.");
I found a good example ,that can use with unity3d here.
Unity's WWW class & method group has been deprecated. Using UnityWebRequest is the current recommended method for handling web requests, especially GET requests:
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class MyBehaviour : MonoBehaviour {
void Start() {
StartCoroutine(GetText());
}
IEnumerator GetText() {
UnityWebRequest www = UnityWebRequest.Get("http://www.my-server.com");
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
}
else {
// Show results as text
Debug.Log(www.downloadHandler.text);
// Or retrieve results as binary data
byte[] results = www.downloadHandler.data;
}
}
}
Yesterday I asked a question and implemented an answer concerning how to send image data from a C# application to a PHP web page ready to receive the POST data, decode it, and display the image.
Here's the C# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Collections.Specialized;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
// Load a image
System.Drawing.Image myImage = GetImage("http://upload.wikimedia.org/wikipedia/commons/5/5b/Ultraviolet_image_of_the_Cygnus_Loop_Nebula_crop.jpg");
// Convert to base64 encoded string
string base64Image = ImageToBase64(myImage, System.Drawing.Imaging.ImageFormat.Jpeg);
// Post image to upload handler
using (WebClient client = new WebClient())
{
byte[] response = client.UploadValues("www.myurl.com", new NameValueCollection()
{
{ "myImageData", base64Image }
});
Console.WriteLine("Server Said: " + System.Text.Encoding.Default.GetString(response));
}
Console.ReadKey();
}
static System.Drawing.Image GetImage(string filePath)
{
WebClient l_WebClient = new WebClient();
byte[] l_imageBytes = l_WebClient.DownloadData(filePath);
MemoryStream l_stream = new MemoryStream(l_imageBytes);
return Image.FromStream(l_stream);
}
static string ImageToBase64(System.Drawing.Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
}
And here's the PHP code:
<?php
// Handle Post
if (count($_POST))
{
// Save image to file
$imageData = base64_decode($_POST['myImageData']);
// Write Image to file
$h = fopen('test.jpg', 'w');
fwrite($h, $imageData);
fclose($h);
// Success
exit('Image successfully uploaded.');
}
// Display Image
if (file_exists('test.jpg'))
{
echo '<img src="test.jpg?_='. filemtime('test.jpg') .'" />';
}
else
{
echo "Image not uploaded yet.";
}
?>
Everything seems to work up to a certain point--I get a console message that says the image was successfully uploaded, but when I visit my webpage, I get a broken image, rather than stating the "Image not uploaded yet". From this I think I can conclude everything is at least working enough to send the data from C# to PHP--it just seems like the encoding/decoding of the image itself is not working properly. Oddly, earlier on in this project, we were doing something similar with encoding and decoding images, but the python code only works in linux--not windows. Linux would give the right image, windows only displayed a broken image with the same code.
Any ideas on what the problem is and how to fix it?
If you choose a different (smaller) image like http://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Banteay_Kdei%2C_Angkor%2C_Camboya%2C_2013-08-16%2C_DD_15.JPG/640px-Banteay_Kdei%2C_Angkor%2C_Camboya%2C_2013-08-16%2C_DD_15.JPG it's working perfectly.
So I'm afraid you're reaching the upload limit for post data, which should be 8MB in PHP by default. The image you're trying to upload is 12MB and Base64 encoded it is close to 20MB.
post_max_size in the php.ini can be modified to increase the post limit. But I highly recommend switching to regular file upload. See WebClient.uploadFile (http://msdn.microsoft.com/en-us/library/36s52zhs(v=vs.110).aspx).
I have a few reports that are exported to Excel. The problem is whereever there are special characters, it is being replaced by some funny symbols
For example, '-'(hyphen) was replaced by –...
Any help to solve the problem??
The most straight forward way is to encode the text file as UTF-8. I ran the following code, opened the resulting hyphen.txt file in Excel 2007 and it worked as expected:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var hyphen = "\u2010\r\n";
var encoding = Encoding.UTF8;
var bytes = encoding.GetBytes(hyphen);
using (var stream = new System.IO.FileStream(#"c:\tmp\hyphen.txt", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
{
stream.Write(bytes, 0, bytes.Length);
}
}
}
}
This is the code -- view at PasteBin.