I am making a program that reads a .tyd file and tries to translate all the text between the " from English to Italian.
GoToDesk translate-> "Looking for computer"
The problem is that I am still getting "Out of memory".
The code is:
using System.Collections;
using System.Net;
using MiscUtil.IO;
namespace Soft_inc
{
class MyProject
{
public static string TranslateText(string input, string languagePair)
{
string url = String.Format("http://translate.google.it/?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
WebClient webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
string result = webClient.DownloadString(url);
result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
result = result.Substring(result.IndexOf(">") + 1);
result = result.Substring(0, result.IndexOf("</span>"));
return result.Trim();
}
public static void Main()
{
string path_file = #"H:\Games\Software.In.v11.7.62\Software.In.v11.7.62\Localization\Italiano\idk\UI.tyd";
string Ftext = System.IO.File.ReadAllText(path_file);
ArrayList ar = new ArrayList();
Console.WriteLine("This may require some time.");
foreach (string line in new LineReader(() => new StringReader(Ftext)))
{
if(line.IndexOf("\"") == -1) continue;
string text = line.Substring(line.IndexOf("\""));
text = text.Replace("\"","");
if(text.Length == 0) continue;
ar.Add(text);
}
int idk = 0;
while(true)
{
idk++;
if(idk == ar.Count) break;
string oldT = (string)ar[idk];
Ftext = Ftext.Replace(oldT, TranslateText(oldT,"en|it"));
}
System.IO.File.WriteAllText("UI.tyd",Ftext);
}
}
}
Maybe it is because the file has 2535 lines of text?
How I can fix this?
You need to use StreamReader class. It is not necessary to read all file content into RAM. Open one StreamReader and one StreamWriter. Reed file line by line and write translated data into a temporary file. When all content is translated just move temp file to needed destination. Don't forget to close source and destination handles before moving.
I'm trying to send percent-encoded ASCII characters using HttpWebRequest, for example https://example.com/%74%65%73%74
Using POSTMAN I'm able to send a request and see in charles that it's still encoded, however, regardless of what I do, any C# library will simplify this to https://example.com/test.
Is there any workaround or async compatible library to work around this?
Thanks in advance
Example Code
string newURL = "";
string path = "test";
foreach (char character in path)
{
string charac = "";
string finished = "";
if (character != '-' || character != '/')
{
if (random.Next(1, 10) >= 5)
{
charac = "%" + Convert.ToInt32(character).ToString("X");
}
else
{
charac = character.ToString();
}
}
newURL = newURL + charac;
}
string main = "http://www.example.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(main + "/en/" + newURL);
Hi i'm trying to download a png file and place it in a custom location and i have tried adding to the line but wc.DownloadFile does not allow 3 arguments. does anyone have a suggestion? (rookie programmer)
if i change wc.DownloadFile to wc.DownloadFileAsync it gives me an error on y[2]
string lookat = args[0];
string[] exploded = lookat.Split('/');
WebClient wc = new WebClient();
wc.Proxy = new WebProxy();
string content = wc.DownloadString(args[0]);
Regex rx = new Regex("data-id=\"(.*)\">");
MatchCollection matches = rx.Matches(content);
string uri = "http://" + exploded[2] + "/v2/photo/=";
string id = matches[0].ToString().Replace("\"", "").Replace(">", "").Replace("data-id=", "");
content = wc.DownloadString(uri + id);
string[] res = content.Split(new string[] { "filetobedownloaded_" }, StringSplitOptions.None);
foreach (string s in res)
{
if (s.Contains(".png"))
{
string[] y = s.Replace("\\", "").Split('"');
wc.DownloadFile(y[2], "filetobedownloaded_" + y[0].Replace("_png", ".jpg"));
}
}
The DownloadFileAsync accepts Uri and not string so you should convert your download link to Uri like this:
wc.DownloadFileAsync(new Uri(y[2]), "C:\\" + "filetobedownloaded_" + y[0].Replace("_png", ".jpg"));
I am programatically trying to POST to a web-service. The issue I face is with my data that I post.
Despite
string post_data = "man=HE&game=01&&address=123 Main St.&cap=1,2,3,4";
new ASCIIEncoding().GetBytes( post_data )
it is not getting converted to
man=HE&game=01&&address=123+Main+St.&cap=1%2C2%2C3%2C4
What is the best way to resolve this?
You are only getting a byte stream that way. In order to URL encode the string you could use the URLEncode method of the HttpUtility helper class:
string post_data = "man=HE&game=01&&address=123 Main St.&cap=1,2,3,4";
string[] postTokens = post_data.Split(new Char [] {'&'});
for(int i = 0; i < postTokens.Length; i++)
{
int pos = postTokens[i].IntexOf("=");
string name = postTokens[i].Substring(0, pos);
string value = postTokens[i].Substring(pos + 1);
postTokens[i] = String.Format("{0}={1}", name, HttpUtility.UrlEncode(value));
}
string encodedPostData = String.Join("=", postTokens);
var encodedPostDataBytes = ASCIIEncoding.GetBytes(encodedPostData);
I think you're confusing ascii encoding with url encoding.
You'll want to use System.Web.HttpServerUtility.UrlEncode method and encode each element of the query string separately.
string post_data =
"man=" + HttpUtility.UrlEncode("HE") +
"&game=" + HttpUtility.UrlEncode("01") // and so forth
I have this method for grabbing the file name from a string URI. What can I do to make it more robust?
private string GetFileName(string hrefLink)
{
string[] parts = hrefLink.Split('/');
string fileName = "";
if (parts.Length > 0)
fileName = parts[parts.Length - 1];
else
fileName = hrefLink;
return fileName;
}
You can just make a System.Uri object, and use IsFile to verify it's a file, then Uri.LocalPath to extract the filename.
This is much safer, as it provides you a means to check the validity of the URI as well.
Edit in response to comment:
To get just the full filename, I'd use:
Uri uri = new Uri(hreflink);
if (uri.IsFile) {
string filename = System.IO.Path.GetFileName(uri.LocalPath);
}
This does all of the error checking for you, and is platform-neutral. All of the special cases get handled for you quickly and easily.
Uri.IsFile doesn't work with http urls. It only works for "file://".
From MSDN : "The IsFile property is true when the Scheme property equals UriSchemeFile."
So you can't depend on that.
Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
Most other answers are either incomplete or don't deal with stuff coming after the path (query string/hash).
readonly static Uri SomeBaseUri = new Uri("http://canbeanything");
static string GetFileNameFromUrl(string url)
{
Uri uri;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
uri = new Uri(SomeBaseUri, url);
return Path.GetFileName(uri.LocalPath);
}
Test results:
GetFileNameFromUrl(""); // ""
GetFileNameFromUrl("test"); // "test"
GetFileNameFromUrl("test.xml"); // "test.xml"
GetFileNameFromUrl("/test.xml"); // "test.xml"
GetFileNameFromUrl("/test.xml?q=1"); // "test.xml"
GetFileNameFromUrl("/test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3#aidjsf"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/a/b/c/d"); // "d"
GetFileNameFromUrl("http://www.a.com/a/b/c/d/e/"); // ""
The accepted answer is problematic for http urls. Moreover Uri.LocalPath does Windows specific conversions, and as someone pointed out leaves query strings in there. A better way is to use Uri.AbsolutePath
The correct way to do this for http urls is:
Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);
I think this will do what you need:
var uri = new Uri(hreflink);
var filename = uri.Segments.Last();
using System.IO;
private String GetFileName(String hrefLink)
{
return Path.GetFileName(hrefLink.Replace("/", "\\"));
}
THis assumes, of course, that you've parsed out the file name.
EDIT #2:
using System.IO;
private String GetFileName(String hrefLink)
{
return Path.GetFileName(Uri.UnescapeDataString(hrefLink).Replace("/", "\\"));
}
This should handle spaces and the like in the file name.
As of 2020, handles query strings & encoded URLs
public static string GetFileNameFromUrl (string url)
{
var decoded = HttpUtility.UrlDecode(url);
if (decoded.IndexOf("?") is {} queryIndex && queryIndex != -1)
{
decoded = decoded.Substring(0, queryIndex);
}
return Path.GetFileName(decoded);
}
this is my sample you can use:
public static string GetFileNameValidChar(string fileName)
{
foreach (var item in System.IO.Path.GetInvalidFileNameChars())
{
fileName = fileName.Replace(item.ToString(), "");
}
return fileName;
}
public static string GetFileNameFromUrl(string url)
{
string fileName = "";
if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
{
fileName = GetFileNameValidChar(Path.GetFileName(uri.AbsolutePath));
}
string ext = "";
if (!string.IsNullOrEmpty(fileName))
{
ext = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(ext))
ext = ".html";
else
ext = "";
return GetFileNameValidChar(fileName + ext);
}
fileName = Path.GetFileName(url);
if (string.IsNullOrEmpty(fileName))
{
fileName = "noName";
}
ext = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(ext))
ext = ".html";
else
ext = "";
fileName = fileName + ext;
if (!fileName.StartsWith("?"))
fileName = fileName.Split('?').FirstOrDefault();
fileName = fileName.Split('&').LastOrDefault().Split('=').LastOrDefault();
return GetFileNameValidChar(fileName);
}
Usage:
var fileName = GetFileNameFromUrl("http://cdn.p30download.com/?b=p30dl-software&f=Mozilla.Firefox.v58.0.x86_p30download.com.zip");
Simple and straight forward:
Uri uri = new Uri(documentAttachment.DocumentAttachment.PreSignedUrl);
fileName = Path.GetFileName(uri.LocalPath);
//First Method to get fileName from fileurl
List<string> fileNameListValues = new List<string>();
//fileNameListValues List consist of fileName and fileUrl
//we need to get fileName and fileurl from fileNameListValues List
name
foreach(var items in fileNameListValues)
{
var fileUrl = items;
var uriPath = new Uri(items).LocalPath;
var fileName = Path.GetFileName(uriPath);
}
//Second Way to get filename from fileurl is ->
fileNameValue = "https://projectname.com/assets\UploadDocuments\documentFile_637897408013343662.jpg";
fileName = " documentFile_637897408013343662.jpg";
//way to get filename from fileurl
string filename =
fileNameValue.Substring(fileNameValue.LastIndexOf("\\") + 1);