I'm trying to get a Text description from a website and used this code
HttpResponseMessage response1 = await httpClient.GetAsync(url);
response1.EnsureSuccessStatusCode();
string srcCode = await response1.Content.ReadAsStringAsync();
string desc = "";
rem = #"id=""full_notes"">";
if (srcCode.IndexOf(rem) != -1)
{
desc = srcCode.Remove(0, srcCode.IndexOf(rem) + rem.Length);
rem = #"less</span>";
desc = desc.Remove(desc.IndexOf(rem));
}
else
{
rem = #"<span>Description:</span>";
desc = srcCode.Remove(0, srcCode.IndexOf(rem) + rem.Length+15);
rem = "</div>";
desc = desc.Remove(desc.IndexOf(rem));
}
string rep = #"""";
desc.Replace(""",rep);
on.Description = desc;
all goes well and I show it in a textblock but the problem comes when the text I get has quotes "" then the textblock would only show " instead of the "
anyone knows how to fix this?
Note: I tried to use replace as shown in the code it didn't work
You're calling Replace but not doing anything with the result - strings are immutable in C#, so the Replace method doesn't change the contents of the existing string. As the documentation states:
This method does not modify the value of the current instance. Instead, it returns a new string in which all occurrences of oldValue are replaced by newValue.
So you'd need:
desc = desc.Replace(""", "\"");
Fundamentally though, I think you'd be better off using an HTML parser (e.g. HTML Agility Pack). That should be able to perform this sort of entity replacement for you.
Related
I will do work with asp.net C#. when I create runtime string (dynamic). After the string, I try to pass the data in the place of data row but I have no idea about that so please provide a proper solution.
Below is my code (code with example )
protected string Replace_Tag(string Email_msg)
{
try {
}
return Email_msg ;
}
After execute this function result found below. (return below string)
"View your all the details" + drmail["WorkName"].ToString() +
"this task is working " + drmail["Cjworkmode"].ToString() + "- " +
drmail["Cjtimeperiod"].ToString() + " "
This is the string so how can I execute this string in for loop and get the proper data.
For loop
string cast_data = Replace_Tag(EditorEmail.Content);
foreach (DataRow drmail in Get_Tab_Data().Tables[0].Rows)
{
String Vie_Data = cast_data;
}
In this for loop how to get below result.
View your all the details XYZ this task is working ABC - 2018
View your all the details ABC this task is working ABC - 2019
View your all the details EFG this task is working MZP - 2017
This is a principle called "string templating". Do some research to find existing solutions. If you don't want to use existing solutions, roll your own.
You could do so by introducing placeholders in the template string:
var templateString = "View all the details {WorkName} this task is working {Cjworkmode} - {Cjtimeperiod}";
Not to be confused with string interpolation, as these placeholders aren't known at compile time.
Then, for example using a regular expression, find all matches in the string:
var placeHolderRegEx = new Regex(#"(\{([a-z]+)\})", RegexOptions.IgnoreCase);
// Copy the string to be templated
var output = templateString;
foreach (Match match in placeHolderRegEx.Matches(templateString))
{
// Replace each instance of `{x}` with the value of `drmail[x]`.
output = output.Replace(match.Groups[1].Value, drmail[match.Groups[2].Value]);
}
There are other similar questions that have been asked and answered, but none of those answers work in what I'm trying to do, or there isn't enough information for me to know how to implement it in my own code. I've been at it for two days and now must ask for help.
I have a script task in an SSIS package where I need to do a match and replace on a large XML file that contains thousands of Record Identifier tags. Each one contains a number. I need those numbers to be consecutive and increment by one. For example, within the xml file, I am able to find tags that appear like this:
<ns1:recordIdentifier>1</ns1:recordIdentifier>
<ns1:recordIdentifier>6</ns1:recordIdentifier>
<ns1:recordIdentifier>223</ns1:recordIdentifier>
<ns1:recordIdentifier>4102</ns1:recordIdentifier>
I need to find and replace those tags with consecutive increments like so:
<ns1:recordIdentifier>1</ns1:recordIdentifier>
<ns1:recordIdentifier>2</ns1:recordIdentifier>
<ns1:recordIdentifier>3</ns1:recordIdentifier>
<ns1:recordIdentifier>4</ns1:recordIdentifier>
The code I have so far is causing all the numbers to be "1" with no incrementation.
I've tried dozens of different methods, but nothing has worked yet.
Any ideas as to how I can modify the below code to increment as desired?
public void Main()
{
string varStart = "<ns1:recordIdentifier>";
string varEnd = "</ns1:recordIdentifier>";
int i = 1;
string path = Dts.Variables["User::xmlFilename"].Value.ToString();
string outPath = Dts.Variables["User::xmlOutputFile"].Value.ToString();
string ptrn = #"<ns1:recordIdentifier>\d{1,4}<\/ns1:recordIdentifier>";
string replace = varStart + i + varEnd;
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null && i>0)
{
File.WriteAllText(outPath, Regex.Replace(File.ReadAllText(path),
ptrn, replace));
i++;
}
}
}
You were on the right path with the Replace method, but will need to use the MatchEvaluater parameter when you increment.
string inputFile = Dts.Variables["User::xmlFilename"].Value.ToString();
string outPutfile = Dts.Variables["User::xmlOutputFile"].Value.ToString();
string fileText = File.ReadAllText(inputFile);
//get any number between elements
Regex reg = new Regex("<ns1:recordIdentifier>[0-9]</ns1:recordIdentifier>");
string xmlStartTag = "<ns1:recordIdentifier>";
string xmlEndTag = "</ns1:recordIdentifier>";
//assuming this starts at 1
int incrementInt = 1;
fileText = reg.Replace(fileText, tag =>
{ return xmlStartTag + incrementInt++.ToString() + xmlEndTag; });
File.WriteAllText(outPutfile, fileText);
I've been trying to do a renamer program in c# for 2 different paths and I keep getting error "Path includes invalid characters" I have no clue how to fix it, I've tried adding # and deleting \ and keeping only one . But still didn't figure out how to fix it. Would love any help.
This is what gives me an error:
if (French.Checked)
{
directoryfile = #"C:\Users\" + curruser + #"\Appdata\Local\fo4renamer\directory.txt";
label1.Text = directoryfile;
readpath = File.ReadAllText(directoryfile);
string shouldwork = readpath + "data";
string french = shouldwork + "\\french";
string german = shouldwork + "\\german";
string tmp = shouldwork + "tmp.txt";
label1.Text = french;
string path2 = #"C:\Users\duchacekda\Desktop\e\Renamer\Renamer\bin\Debug\tmp.txt";
string filename = #"C:\Users\duchacekda\Desktop\e\Renamer\Renamer\bin\Debug\french.txt";
File.Move(french, german);
}
Here is the whole code:
https://pastebin.com/0i7fzh24
Edit: this is the string for curruser
string curruser = System.Environment.UserName;
The exception was given by this line
File.Move(french, german);
File.ReadAllText Method (String) : Opens a text file, reads all lines of the file, and then closes the file.
So in your scenario :
string french = (Content of directory.txt) + "data" + "\\french";
It depends on content of directory.txt
a) If content = directory path(c:\foo) there is no problem
b) if content = "dummy text *** dummy text" then it will throw exception
Please check content of file
Found the mistake, I used WriteLine instead of Write so it added enter on the end of the line which made the path incorrect, thanks for the help
So, I'm making a file transfer program from one PC in my house to the other. The client can look through the server's files and take what it wants. (Makes it very easy for moving projects/documents/music). This is an example of what a string of a file looks like:
New Text Document.txt : "(FILE)-(" + f.Length + " Bytes)"
My problem is removing : "(FILE)-(" + f.Length + " Bytes)".
How can I remove JUST that part from the string? Where the f.Length is unknown...
Thanks!
Just as an alternative to the regex answers, one option is to use LastIndexOf to find the last occurence of a known part of the string (e.g. (FILE)).
var oldString = "ThisIsAString (FILE)-(1234 Bytes";
int indexToRemoveTo = oldString.LastIndexOf("(FILE)");
// Get all the characters from the start of the string to "(FILE)"
var newString = oldString.Substring(0, indexToRemoveTo);
I hope I've got what you want
string contents = "some text (FILE)-(5435 Bytes) another text";
string result = Regex.Replace(contents, #"\(FILE\)-\(\d+ Bytes\)", "");
Console.WriteLine (result);
Prints:
some text another text
Solution to remove everything after .txt
string contents = "some text .txt (FILE)-(5435 Bytes) another text";
string lastSegment = ".txt";
var result = contents.Substring(0, contents.IndexOf(lastSegment) + lastSegment.Length);
Console.WriteLine (result);
prints some text .txt
var match = Regex.Match(pattern: #"\((.*)\)-\(\d+ Bytes\)$", input: name);
if(match.Success)
{
string fileName = match.Groups[1].Value;
}
I've the following code, which builds up a Roslyn statement which calls Roslyn code inside, but I've a problem with string escaping.
Here is the code:
var parseStatementArgument = "var statement = Syntax.ParseStatement(\\\"Console.WriteLine (\\\"Hello {0}\\\", parameter1);\\\");";
var st = Syntax.InvocationExpression(
Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, Syntax.IdentifierName("Syntax"), Syntax.IdentifierName("ParseStatement")))
.AddArgumentListArguments(
Syntax.Argument(Syntax.LiteralExpression(
SyntaxKind.StringLiteralExpression,
Syntax.Literal(
text: "\"" + parseStatementArgument + "\"",
value: parseStatementArgument)
)));
var variableDeclarator = Syntax.VariableDeclarator(Syntax.Identifier("statement"))
.WithInitializer(Syntax.EqualsValueClause(st));
var varStatement = Syntax.VariableDeclaration(Syntax.IdentifierName("var"), Syntax.SeparatedList(variableDeclarator));
var varStatementText = varStatement.Format().GetFormattedRoot().GetFullText() + ";";
var scriptEngine = new ScriptEngine(
new [] {
MetadataReference.Create("Roslyn.Compilers"),
MetadataReference.Create("Roslyn.Compilers.CSharp"),
MetadataReference.Create("Roslyn.Services"),
MetadataReference.Create("Roslyn.Services.CSharp")
},
new [] {
"System",
"Roslyn.Compilers.CSharp",
"Roslyn.Scripting",
"Roslyn.Scripting.CSharp",
"Roslyn.Services"
});
var session = Session.Create();
scriptEngine.Execute(varStatementText, session);
scriptEngine.Execute("Console.WriteLine (statement.Format().GetFormattedRoot().GetFullText());", session);
The problem is that the "statement" printed to the console windows via the script engine execution will miss the backslashed around the "Hello {0}" string. If I add double escaping (additional \ into the parameter, Roslyn will raise compile errors about missing commas.
How may I update this code to get a syntactically correct version of what I want into the statement variable?
How about switching to using verbatim string levels, and just add another level of escaping as you add the node.
Something like:
var parseStatementArgument = #"var statement = Syntax.ParseStatement(#""Console.WriteLine (""""Hello {0}"""", parameter1);"");";
var st = Syntax.InvocationExpression(
Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, Syntax.IdentifierName("Syntax"), Syntax.IdentifierName("ParseStatement")))
.AddArgumentListArguments(
Syntax.Argument(Syntax.LiteralExpression(
SyntaxKind.StringLiteralExpression,
Syntax.Literal(
text: "#\"" + parseStatementArgument.Replace("\"", "\"\"") + "\"",
value: parseStatementArgument)
)));
Based on Kevin's tip on how to replace string for literals I played around and found this as a solution that works, but it raised another problem.
The solution:
var parseStatementArgument = "var statement = Syntax.ParseStatement(\\\"Console.WriteLine (\\\\\\\"Hello {0}\\\\\\\", parameter1);\\\");";
var st = Syntax.InvocationExpression(
Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, Syntax.IdentifierName("Syntax"), Syntax.IdentifierName("ParseStatement")))
.AddArgumentListArguments(
Syntax.Argument(Syntax.LiteralExpression(
SyntaxKind.StringLiteralExpression,
Syntax.Literal(
text: "\"" + parseStatementArgument + "\"",
value: parseStatementArgument.Replace ("\\\\\\", "\\"))
)));
Now it correctly outputs a code snippet which is syntactically correct and compiles well.
The problem it raises is that I had to modify the source string and not the derived string to get the correct result. When rewriting code or generating code with Roslyn it can not be a requirement to double or triple escape string literals to make Roslyn able to deal with that correctly, maybe its a Roslyn issue, I hope that someone will shed some light on an elegant solution which works for all kind of strings.