Get the remaining text after subtring - c#

how can I get the remaining text/values of ImageString and return it in a variable? In my current code below i got an error.
Note: ImageString = data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAOEAlgDASIAAhEBAxEB/8QAHQABAAICAwEBAAAAAAAAAAAAAAUGAwQBAgcICf/EAEkQAQABAwMCAgcCDAMFBgcAAAABAgMEBREhMTIGEgciQVFhcYETkQgUIzNCUnKCobHB0RVikkNjc7LwFhckNKL
var _strings= { response = "True", name = "John", ImageString = "(random text here (1-1000 of characters maybe?))"};
var _split = _strings.Substring(_strings.IndexOf("ImageString"), _strings.Length);
"Index and length must refer to a location within the string.
Expected Out : I want to get all the text from the "ImageString"

In your particular case you can use JSON serializer:
public class Data
{
public string ImageString { get; set; }
}
var data = Newtonsoft.Json.JsonConvert.Deserialize<Data>(_strings);
var myImageString = data.ImageString;

var _strings= { response = "True", name = "John", ImageString = "(random text here (1-1000 of characters maybe?))"};
The above looks like an anonymous object but i am assumming you mean the structure of your text by it.
var imageStringIndex= _strings.IndexOf("ImageString");
var _split = _strings.Substring(imageStringIndex<0?0:imageStringIndex, _strings.Length - 1);
or
var _split = _strings.Split("ImageString".ToCharArray()).Last();
both you work for your case

If I've understood you right, and you insist on string manipulations (not Json parsing)
string _strings =
"{ response = \"True\", name = \"John\", ImageString = \"bla-bla-bla\" };";
string toFind = "ImageString";
int p = _strings.IndexOf(toFind);
// bla-bla-bla
string remain = p < 0
? "" //TODO: Not found at all (shall we return an empty or entire string?)
: _strings
.Substring(p + toFind.Length)
.TrimStart(' ', '=') // to be on the safe side: what if data starts from =
.TrimStart('"', ' ')
.TrimEnd('}', ';', ' ')
.TrimEnd('"', ' ');

First problem I'm seeing is that
var _strings= { response = "True", name = "John", ImageString = "(random text here (1-1000 of characters maybe?))"};
Is not a string, rather an attempt at an anonymous object?
If it is, you can declare the object using:
var _strings = new { response = "True", name = "John", ImageString = "(random text here (1-1000 of characters maybe?))" };
Then access any property in the object using standard c# syntax:
var imageString = _strings.ImageString;
The answer to your question depends very much on where the information is coming from as you can declare it and manipulate it in a thousand different ways if you have control over it.

Related

C# Trying to split a string to get json object value

I am trying to split a string to get json object value - I have text values with numerous lines in the format:
new Car() { Id = 1, Year = 1926, Make = "Chrysler", Model = "Imperial", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRPe4CygIW-MuZL5jl77wlgXXK5_ANyC9l1X4QqLizCOkaVAlRe","image_url":"http://imperialclub.org/Yr/1926/photos/Phaeton2Big.jpg","width":1632,"height":1032}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
new Car() { Id = 2, Year = 1950, Make = "Hillman", Model = "Minx Magnificent", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcScVsGEeRBh6xZYXr6Gm35Sk5ecSlk_ax3qZmoGRAtBbZC8vJZ9","image_url":"http://i.ebayimg.com/images/g/gcIAAOSwKadXPeLs/s-l300.jpg","width":300,"height":225}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
new Car() { Id = 3, Year = 1954, Make = "Chevrolet", Model = "Corvette", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSdZntu4tgWrZrxwqeuKlteCP9vJGnqUlmNq5JF1bBCf-EJy5r8","image_url":"http://momentcar.com/images/chevrolet-corvette-1954-1.jpg","width":1000,"height":600}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
What I would really like is to get them in the format:
new Car() { Id = 1, Year = 1926, Make = "Chrysler", Model = "Imperial", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRPe4CygIW-MuZL5jl77wlgXXK5_ANyC9l1X4QqLizCOkaVAlRe" },
new Car() { Id = 2, Year = 1950, Make = "Hillman", Model = "Minx Magnificent", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcScVsGEeRBh6xZYXr6Gm35Sk5ecSlk_ax3qZmoGRAtBbZC8vJZ9" },
new Car() { Id = 3, Year = 1954, Make = "Chevrolet", Model = "Corvette", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSdZntu4tgWrZrxwqeuKlteCP9vJGnqUlmNq5JF1bBCf-EJy5r8" },
I know I can use JObject.Parse(data); to parse the json value - but just tring to get to it is becoming a bit of a nightmare. Is there a better way of doing this?
What I have so far:
static void Main(string[] args)
{
using (StreamWriter writer = new StreamWriter(#"c:\Data\temp\output.txt")) // file to write to
{
using (StreamReader reader = new StreamReader(#"c:\Data\temp\test.txt")) //file to read from
{
string line;
while (reader.ReadLine() != null)
{
line = reader.ReadLine();
string[] words = JsonSplitString(line);
string json = words[1];
writer.WriteLine("{0}", json);
}
}
}
}
static string[] JsonSplitString(string data)
{
return data.Split(new string[] { "ImageUrl" }, StringSplitOptions.None);
}
However I am getting a NullReferenceException - even though a string is being passed in to the JsonSplitString method.
You are calling reader.Readline() twice: once for the comparison and then again inside your loop. You are actually skipping every other line. And what is probably happening is that you are reaching the end of your file and then calling reader.Readline() again, which is null. Try this instead:
line = reader.ReadLine();
while (line != null)
{
string[] words = JsonSplitString(line);
string json = words[1];
writer.WriteLine("{0}", json);
line = reader.ReadLine();
}
using System;
using Newtonsoft.Json.Linq;
namespace JsonExperiments
{
class Program
{
static void Main(string[] args)
{
ExecuteEmployeeSearch();
Console.ReadLine();
}
static void ExecuteEmployeeSearch()
{
// mockup JSON that would be returned from API
string sampleJson = "{\"results\":[" +
"{\"employeename\":\"name1\",\"employeesupervisor\":\"supervisor1\"}," +
"{\"employeename\":\"name2\",\"employeesupervisor\":\"supervisor1\"}," +
"{\"employeename\":\"name3\",\"employeesupervisor\":[\"supervisor1\",\"supervisor2\"]}" +
"]}";
// Parse JSON into dynamic object, convenient!
JObject results = JObject.Parse(sampleJson);
// Process each employee
foreach (var result in results["results"])
{
// this can be a string or null
string employeeName = (string)result["employeename"];
// this can be a string or array, how can we tell which it is
JToken supervisor = result["employeesupervisor"];
string supervisorName = "";
if (supervisor is JValue)
{
supervisorName = (string)supervisor;
}
else if (supervisor is JArray)
{
// can pick one, or flatten array to a string
supervisorName = (string)((JArray)supervisor).First;
}
Console.WriteLine("Employee: {0}, Supervisor: {1}", employeeName, supervisorName);
}
}
}
}

How to filter values read from a text file

I want to get a couple of values from a textfile in C#. Example:
1.sex=male
1.name=barack
1.lastname=obama
1.age = 55
2.sex=female
2.name= kelly
2.lastname=clinton
2.age = 24
3.sex = male
3.firstname= mike
3.lastname= james
3.age= 19
I only want to get all the "name", "lastname" and ages from the textFile, not the "sex". How can I filter this? I have tried something like this, but it only shows 1 value.
var list = new List<string>();
var text = File.ReadAllLines(#"C:\Users\Jal\Desktop\Test.text");
foreach (var s in text)
{
if (s.Contains("Name"))
{
if (s.Contains("Name"))
{
var desc = s.Substring(s.IndexOf("=") + 1);
list.Add(desc);
ListView.Items.Add(desc);
}
}
}
I found this code on Stack Overflow, but it doesn't get all of the values I want.
var names = new List<string>();
var lastnames = new List<string>();
var text = File.ReadAllLines(#"C:\Users\Jal\Desktop\Test.text");
foreach (var s in text)
{
if (s.Contains("lastname"))
{
var lastname = s.Substring(s.IndexOf("=") + 1);
lastnames.Add(lastname);
continue;
}
if (s.Contains("name"))
{
var name = s.Substring(s.IndexOf("=") + 1);
names.Add(name);
continue;
}
}
And in same way you can add another properties.
s.Contains("Name") won't ever be true on this case because it's case-sensitive, and your string in the file is "name".
Try using s.Contains("name")
But you would be better off using a Regex for this kind of thing.

C# separating data within a line from a text file

I have a data file
Name; LastName; EurosCents;
Name2; LastName2; EurosCents2;
(for example:
John; Smith; 4,20;
Josh; Peck; 6,50;
)
I need to read the data and then do some further work with it... Is there any way to read the lines and save them? As the only way to read from a text file is to read the entire line at once.
var lst = File.ReadAllLines(yourFilePath).Select(x => new
{
FirstName = x.Split(';')[0]
LastName = x.Split(';')[1]
Value = decimal.Parse(x.Split(';')[2])
}).ToList();
use
lst[7].FirstName = "xxx";
Console.WriteLine(lst[2].Value);
etc...
The File API provide multiple options for reading files. Below is a possible way to proceed:
foreach(var line in File.ReadAllLines(path))
{
var splitted = line.Split(';');
var name = splitted.ElementAtOrDefault(0);
var lastName = splitted.ElementAtOrDefault(1);
var cents = Decimal.Parse(splitted.ElementAtOrDefault(2));
}
Parsing will be very easy if you are comfortable using LINQ.
Below line can get you the file in a hierarchical structure.
var theselines = File.ReadLines(#"C:\Test.txt").Select(l => l.Split(','));
You can see the result of above line by debugging.
Later you can have any logic to get the required data from each line without using foreach loop.
var Data = theselines.Select(l => new
{
id = l.Where(t => t.Contains("01")).FirstOrDefault(),
Price = l.Where(t => t.Contains(",")).FirstOrDefault(),
Firstname= l[0],
lastname = l[1]
});
Providing that data itself (both names and cents) can't contain ; in order to get
items from the comma separated values you can just split:
var data = File
.ReadLines(#"C:\MyData.csv")
// .Skip(1) // <- in case you have caption to skip
.Select(line => line.Split(';'))
.Select(items => new {
Name = items[0],
LastName = items[1],
EuroCents = decimal.Parse(items[2]) //TODO: check type and its format
});
//.ToArray(); // <- if you want to materialize as, say, an array
Then you can use it
foreach (var item in data) {
if (item.EuroCents > 10) {
...
}
}
the simple code to read whole file is as follows
string[] test(string path)
{
System.IO.StreamReader sr = new System.IO.StreamReader(path);
string[] str = sr.ReadToEnd().Split(';');
sr.Close();
return str;
}

Can't get Regex group value

The string I'm trying to parse from looks something like this:
{"F4q6i9xe":{"Hhgi79M1":"cTZ3W2JG","j0Uszek2":"0"},"a3vSYuq2":{"Kn51uR4Y":"c6QUklQzv+kRLnmvS0zsheqDsRCXbWFVpYhq2rsElKyFQnla01E6P3qQ26b+xWSrscFJCi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Tx3jVrAeXcHGFjZtxbk3pFmuqPqgVcxeX/aDbK0NHkR6phQcFEREBjfdCOLAAbCkWiRF0JAA=="}}
And this is my regular expression:
Hhgi79M1":"(?<encodeKeyID>.*?)",.*Kn51uR4Y":"(?<encodedBody>.*?)"}
And this is the code I'm using in my C# application:
string responsePattern = "Hhgi79M1\":\"(?<encodeKeyID>.*?)\",.*Kn51uR4Y\":\"(?<encodedBody>.*?)\"}";
if (Regex.IsMatch(body, responsePattern))
{
var match = Regex.Match(body, responsePattern);
string encodeKeyID = match.Groups["encodeKeyID"].Value;
string encodedBody = match.Groups["encodedBody"].Value;
Now it works, but it doesn't get the value of "encodedBody". I tested my expression with the data on https://regex101.com/ and it seems to work fine on there. However, when getting the value in my program it's just an empty string.
I sense the issue is that your body string is not escaped properly, as your pattern works fine in the following code:
string body = "{\"F4q6i9xe\":{\"Hhgi79M1\":\"cTZ3W2JG\",\"j0Uszek2\":\"0\"},\"a3vSYuq2\":{\"Kn51uR4Y\":\"c6QUklQzv+kRLnmvS0zsheqDsRCXbWFVpYhq2rsElKyFQnla01E6P3qQ26b+xWSrscFJCi2qsh6WjJKSW5FN9EwxRAWc3rfyToaEhRngI2WPu3W/b1/hkkS2tEEk7LEpS2ItxLYKjEQGneO5E9rcGzbtfSOikdIjhxpD5m9HsKayo2ZSc2EYd/cN9yfYrNfLOCx+xeGqGcPmmImAzOZM0Q1IXIDQZ5r70vUS1aUOMOFnN1fVxmQ8ISofEKNEpHFfwWW9QUl9eVDgpQ2HES13s20kvVH2FOlE5uahIJBnyTLWYzViAWYyX13VK2PgrQcZ0oLuV84bSbjHGZf+JAjvImuyYhkKDhtTWAGkQ8LZ6r07duo71Gbz3glOUZZyz+FFiH5KrwafBpzGhRlI8El6lLZASN9Z5iZNTKs+sOti1fzsuOBzUXEjFURJGa93GMqPC+OyTw6YxKvgapz7go1XL7EAf50UXpMHd9xAJzsuIb6/lB/6v+XjD70wc74D2OosxtR6DIbQj3gbaBUBABQsJHQZLNnHWqikh+HLCASVbkqw6YPm5NecGaOQxonDkh3ZVQSF15WCEsgNdoWG94OuLF8DSw1t1Kt8sMFkvBJgB7LJS3pAw/Tcg/rvR5qwZ/n31rtOzaJgCdVc6XeIK6Rttj4KvNtgtTwkJIjb97FgIS0CXrR0UCp3BsuLwQg3CRTnjQqsjGgJeinLXX2lq6vNOkxRzgXlWnap96kheYj7sIE/IxbJJWEIInMbH9HU/w0bS0MtIgofpIQAZ/m6XKhu9LpPZBgsBf9KX5chUPeuRfs3MfHFzPYPlCCd2dkE8BHKOTmfS3okqhkzIZvFN3Ni+7enktFdgfpQ0toQbjhpn/TszP34pBaIy77me+GvePNO5bAFECLWSpGvsmW16rLCP0H+xIS/lNf9hK98jQqGU7eqpQdai7WFie2yN75Up7MrgBMp5w9Z5C7qpG2iYGiqynpqTCEnfQ3IZumbL+YvGTiuI2c320MGjKzOdO45MIU5fxUNZQSIfCSyIq5G/XGIeXCG3KETyKDZygXUTgEWbJWNTADE0AhXvP7HMtsuvstyuHvlTZGcfKS4oLnDPFiV1ndIV7+W74Ytv9bAdDIVl36xTzA2PV6waqXBfSPUCTx3jVrAeXcHGFjZtxbk3pFmuqPqgVcxeX/aDbK0NHkR6phQcFEREBjfdCOLAAbCkWiRF0JAA==\"}}\n" +
"";
string responsePattern = "Hhgi79M1\":\"(?<encodeKeyID>.*?)\",.*Kn51uR4Y\":\"(?<encodedBody>.*?)\"}";
if (Regex.IsMatch(body, responsePattern))
{
var match = Regex.Match(body, responsePattern);
string encodeKeyID = match.Groups["encodeKeyID"].Value;
string encodedBody = match.Groups["encodedBody"].Value;
string msg = String.Format("encodeKeyID: {0}\nencodedBody: {1}", encodeKeyID, encodedBody);
//show in message box
MessageBox.Show(msg, "Pattern Match Result");
}
Output:
Try it this way.
string sTarget = #"
{""F4q6i9xe"":{""Hhgi79M1"":""cTZ3W2JG"",""j0Uszek2"":""0""},""a3vSYuq2"":{""Kn51uR4Y"":""c6QUklQzv+kRLnmvS0zsheqDsRCXbW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KS4oLnDPFiV1ndIV7+W74Ytv9bAdDIVl36xTzA2PV6waqXBfSPUCTx3jVrAeXcHGFjZtxbk3pFmuqPqgVcxeX\/aDbK0NHkR6phQcFEREBjfdCOLAAbCkWiRF0JAA==""}}
";
Regex responseRx = new Regex(#"Hhgi79M1"":""(?<encodeKeyID>.*?)"",.*Kn51uR4Y"":""(?<encodedBody>.*?)""}");
Match responseMatch = responseRx.Match(sTarget);
if (responseMatch.Success)
{
Console.WriteLine("ID = {0}", responseMatch.Groups["encodeKeyID"].Value);
Console.WriteLine("Body = {0}", responseMatch.Groups["encodedBody"].Value);
}
Output
ID = cTZ3W2JG
Body = c6QUklQzv+kRLnmvS0zsheqDsRCXbWFVpYhq2rsElKyFQnla01E6P3qQ26b+xWSrscFJCi2qs
h6WjJKSW5FN9EwxRAWc3rfyToaEhRngI2WPu3W\/b1\/hkkS2tEEk7LEpS2ItxLYKjEQGneO5E9rcGzb
tfSOikdIjhxpD5m9HsKayo2ZSc2EYd\/cN9yfYrNfLOCx+xeGqGcPmmImAzOZM0Q1IXIDQZ5r70vUS1a
UOMOFnN1fVxmQ8ISofEKNEpHFfwWW9QUl9eVDgpQ2HES13s20kvVH2FOlE5uahIJBnyTLWYzViAWYyX1
3VK2PgrQcZ0oLuV84bSbjHGZf+JAjvImuyYhkKDhtTWAGkQ8LZ6r07duo71Gbz3glOUZZyz+FFiH5Krw
afBpzGhRlI8El6lLZASN9Z5iZNTKs+sOti1fzsuOBzUXEjFURJGa93GMqPC+OyTw6YxKvgapz7go1XL7
EAf50UXpMHd9xAJzsuIb6\/lB\/6v+XjD70wc74D2OosxtR6DIbQj3gbaBUBABQsJHQZLNnHWqikh+HL
CASVbkqw6YPm5NecGaOQxonDkh3ZVQSF15WCEsgNdoWG94OuLF8DSw1t1Kt8sMFkvBJgB7LJS3pAw\/T
cg\/rvR5qwZ\/n31rtOzaJgCdVc6XeIK6Rttj4KvNtgtTwkJIjb97FgIS0CXrR0UCp3BsuLwQg3CRTnj
QqsjGgJeinLXX2lq6vNOkxRzgXlWnap96kheYj7sIE\/IxbJJWEIInMbH9HU\/w0bS0MtIgofpIQAZ\/
m6XKhu9LpPZBgsBf9KX5chUPeuRfs3MfHFzPYPlCCd2dkE8BHKOTmfS3okqhkzIZvFN3Ni+7enktFdgf
pQ0toQbjhpn\/TszP34pBaIy77me+GvePNO5bAFECLWSpGvsmW16rLCP0H+xIS\/lNf9hK98jQqGU7eq
pQdai7WFie2yN75Up7MrgBMp5w9Z5C7qpG2iYGiqynpqTCEnfQ3IZumbL+YvGTiuI2c320MGjKzOdO45
MIU5fxUNZQSIfCSyIq5G\/XGIeXCG3KETyKDZygXUTgEWbJWNTADE0AhXvP7HMtsuvstyuHvlTZGcfKS
4oLnDPFiV1ndIV7+W74Ytv9bAdDIVl36xTzA2PV6waqXBfSPUCTx3jVrAeXcHGFjZtxbk3pFmuqPqgVc
xeX\/aDbK0NHkR6phQcFEREBjfdCOLAAbCkWiRF0JAA==

If statement that is never called

I have this piece of code
Category featured = new Category()
{
active = true,
Categories = new Category[0],
description = "",
identifier = "featured",
name = "Featured",
Products = new Product[0],
url = siteUrl,
};
StatisticCounters.CategoriesCounter();
then below this I have this code.
private IList<Category> FeatureSubCategories(HtmlNode std, Category category,Category featured)
{
List<Category> categories = new List<Category>();
{
if (category.name == "Featured")
{
var nodes = std.SelectNodes("//span[contains(#class,'widget')] [position() <= 4]"); //TODO
foreach (var node in nodes)
{
string name = SiteParserUtilities.ParserUtilities.CleanText(System.Net.WebUtility.HtmlDecode(node.InnerText));
string url = node.Attributes["href"].Value;
string identifier = url.Split('/').Last().Replace(".html", "");
WriteQueue.write(string.Format(" Category [{0}].. {1} ", name, url));
IList<Category> sub = GetSubCategories(std);
Category c = new Category()
{
active = true,
Categories = sub.ToArray(),
description = "",
identifier = identifier,
name = name,
Products = new Product[0],
url = url,
};
StatisticCounters.CategoriesCounter();
categories.Add(c);
}
}
}
return categories;
}
for some reason tho when I run the code the if statement if (category.name == "Featured") is never called and I am not sure why this is. To start to parse the xpath and store them links into an array. Thank you for any help which you can give.
It is best to check in debugger. Some times whites spaces cause the problem. It is simple mistake done by many programmers. When we get data from database, there may be some leading spaces. When we compare with some value (thinking that there is no leading space), it will not compare without trimming those spaces. For example
string s1 = "TEST";
string s2 = " TEST";
if (s1 == s2) {
Console.WriteLine("Equal");
}
Please use trim function to remove any white spaces and compare.

Categories