Not reading new lines from txt file on webserver - c#

In this script, I'm trying to read lines of a txt file on my web server and display it to a list box but it is not reading new lines!
public byte[] GetFileViaHttp(string url)
{
using (WebClient client = new WebClient())
{
return client.DownloadData(url);
}
}
private void Form1_Load(object sender, EventArgs e)
{
var result = GetFileViaHttp(#"https://www.lunabooster.com/list/script-list.txt");
string str = Encoding.UTF8.GetString(result);
string[] strArr = str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < strArr.Length; i++)
{
OpenSourceListBox.Items.Add(strArr[i].ToString());
}
}

I test your code and work fine if you change \r\n to \n .
Change this :
string[] strArr = str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
To:
//
string[] strArr = str.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

Related

How can I output all the string arrays in a split string?

I've written this code that splits "#" and ":"
var Split = Texts.Split(new char[] { '#' });
var Split1 = Texts.Split(new char[] { ':' });
I want to output all the string arrays to a file. I've tried and I get only one string, not all.
formatted = Split[0] + ":" + Split1[1];
File.WriteAllText(outputfile, formatted);
Here is my code:
public void CreateUsernameList(string targetfile,string outputfile)
{
string[] texts = File.ReadAllLines(targetfile);
string formatted = null;
foreach(string Texts in texts)
{
var Split = Texts.Split(new char[] { '#' });
var Split1 = Texts.Split(new char[] { ':' });
formatted = Split[0] + ":" + Split1[1];
File.WriteAllText(outputfile, formatted);
}
}
You are continuously overwriting the file in that loop. Instead collect the results in a List<string> and then write that to the file.
public void CreateUsernameList(string targetfile,string outputfile)
{
string[] texts = File.ReadAllLines(targetfile);
string formatted = null;
List<string> output = new List<string>();
foreach(string Texts in texts)
{
var Split = Texts.Split(new char[] { '#' });
var Split1 = Texts.Split(new char[] { ':' });
formatted = Split[0] + ":" + Split1[1];
output.Add(formatted);
}
File.WriteAllLines(outputfile, output)
}
An alternative that will not use as much memory would be
public void CreateUsernameList(string targetfile,string outputfile)
{
File.WriteAllLines(
outputfile,
File.ReadLines(targetfile)
.Select(line =>
{
var Split = line.Split(new char[] { '#' });
var Split1 = line.Split(new char[] { ':' });
return Split[0] + ":" + Split1[1];
}
)
);
}
As I dont see any format of data I can only guess that the error might be here:
formatted = Split[0] + ":" + Split1[1];
you are taking only single elements from each array of strings. try looping through all the elements in arrays Split and Split1 to print their values
It's better to read file in lazy manner:
File.ReadLines(targetfile).ForEach(line =>
{
File.AppendAllText("path", string.Join(":", Regex.Split(line, "#|:")
.Cast<Match>().Select(m => m.Value)));
});
static class ExtensionMethods
{
internal static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{
if (enumerable == null) throw new NullReferenceException($"'{nameof(enumerable)}' argument is null");
using var enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext()) action(enumerator.Current);
}
}

How to split by multiple strings in C#

My Question consists of how might i split a string like this:
""List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2
\tdevice\r\n\r\n"
Into:
[n9887bc314,n12n1n2nj1jn2]
I have tried this but it throws the error "Argument 1: cannot convert from 'string' to 'char'"
string[] delimiterChars = new string[] {"\\","r","n","tdevice"};
string y = output.Substring(z+1);
string[] words;
words = y.Split(delimiterChars, StringSplitOptions.None);
I'm wondering if i'm doing something wrong because i'm quite new at c#.
Thanks A Lot
First of all String.Split accept strings[] as delimiters
Here is my code, hope it will helps:
string input = "List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] delimiterChars = {
"\r\n",
"\tdevice",
"List of devices attached"
};
var words = input.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
{
Console.WriteLine(word);
}
Split the whole string by the word device and then remove the tabs and new lines from them. Here is how:
var wholeString = "List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
var splits = wholeString.Split(new[] { "device" }, StringSplitOptions.RemoveEmptyEntries);
var device1 = splits[1].Substring(splits[1].IndexOf("\n") + 1).Replace("\t", "");
var device2 = splits[2].Substring(splits[2].IndexOf("\n") + 1).Replace("\t", "");
I've been doing a first aproach and it works, it might help:
I splited the input looking for "/tdevice" and then cleaned everyting before /r/n including the /r/n itself. It did the job and should work with your adb output.
EDIT:
I've refactored my answer to consider #LANimal answer (split using all delimiters) and I tried this code and works. (note the # usage)
static void Main(string[] args)
{
var inputString = #"List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] delimiters = {
#"\r\n",
#"\tdevice",
#"List of devices attached"
};
var chunks = inputString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string result = "[";
for (int i = 0; i < chunks.Length; i++)
{
result += chunks[i] + ",";
}
result = result.Remove(result.Length - 1);
result += "]";
Console.WriteLine(result);
Console.ReadLine();
}
I hope it helps,
Juan
You could do:
string str = #"List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] lines = str.Split(new[] { #"\r\n" }, StringSplitOptions.None);
string firstDevice = lines[1].Replace(#"\tdevice", "");
string secondDevice = lines[2].Replace(#"\tdevice", "");

Save only end line

I have problem with reading a file.
I must write program which take numbers from polish lottery(saved in .txt) and add this to list and answer to questions.
Anyway.. My algorithm save only end line.. I should save all lines in List.. :)
string line;
List<Losuj> losowanko = new List<Losuj>();
Losuj pomocnik = new Losuj();
StreamReader file =
new StreamReader(#"D:\bawmy się\2# apka\Lotto\Lotto\plik.txt");
while ((line = file.ReadLine()) != null)
{
// Console.WriteLine(line);
string[] podzialka = line.Split(new string[] { ".", " ", "," }, StringSplitOptions.None);
pomocnik.NumerLosowania = Int32.Parse(podzialka[0]);
pomocnik.JakiDzien = Int32.Parse(podzialka[2]);
pomocnik.JakiMiesiac =Int32.Parse(podzialka[3]);
pomocnik.JakiRok=Int32.Parse(podzialka[4]);
for (int i = 5, lo=0; i < 11; i++,lo++)
{
pomocnik.Los[lo] =Int32.Parse(podzialka[i]);
}
losowanko.Add(pomocnik);
}
file.Close();
move Losuj object create line to inside the while loop, otherwise you are changing and adding same object again and again
using(StreamReader file =
new StreamReader(#"D:\bawmy się\2# apka\Lotto\Lotto\plik.txt"))
{
while ((line = file.ReadLine()) != null)
{
Losuj pomocnik = new Losuj();
// Console.WriteLine(line);
string[] podzialka = line.Split(new string[] { ".", " ", "," }, StringSplitOptions.None);
pomocnik.NumerLosowania = Int32.Parse(podzialka[0]);
pomocnik.JakiDzien = Int32.Parse(podzialka[2]);
pomocnik.JakiMiesiac =Int32.Parse(podzialka[3]);
pomocnik.JakiRok=Int32.Parse(podzialka[4]);
for (int i = 5, lo=0; i < 11; i++,lo++)
{
pomocnik.Los[lo] =Int32.Parse(podzialka[i]);
}
losowanko.Add(pomocnik);
}
}
In order to avoid such errors (wrong list items creation) I suggest generating losowanko via Linq. You should
read the file by lines
split each line
create Losuj instance
materialize the IEnumerable<Losuj> into List<Losuj>
Implementation:
List<Losuj> losowanko = File
.ReadLines(#"D:\bawmy się\2# apka\Lotto\Lotto\plik.txt")
.Select(line => line.Split(new string[] { ".", " ", "," }, StringSplitOptions.None))
.Select(items => {
Losuj item = new Losuj() {
NumerLosowania = Int32.Parse(items[0]),
JakiDzien = Int32.Parse(items[2]),
JakiMiesiac = Int32.Parse(items[3]),
JakiRok = Int32.Parse(items[4])};
for (int i = 5, lo = 0; i < 11; i++, lo++)
item[lo] = Int32.Parse(items[i]);
return item;})
.ToList();

How to store all values in the key named folder using c#

I wrote a text file. The first item of each line from this text file supposed to be key and rest of the items are values. My text file looks like this-
Flensburg;Nordertor;Naval Academy Mürwik;Flensburg Firth
Kiel;Laboe Naval Memorial;Zoological Museum of Kiel University;Kieler Förde
Lübeck;Holstentor;St. Mary's Church, Lübeck;Passat (ship);Burgtor;Lübeck Museum of Theatre Puppets;Trave
For my project purpose, I need to create .json data for each values and store those vales into the key name folder.As I am very new handling this situation I am not getting the correct logic to do this. However I tried in the follwing way by which I can create the key name folder and and only one subfolder into it. But I need to create all values folder inside the key folder. How can I do it.
My POI class from which I read the text file as key value is-
public class POI
{
Dictionary<string, List<string>> poi = new Dictionary<string, List<string>>();
public bool ContainsKey(string key) { return this.poi.ContainsKey(key); }
public List<string> GetValue(string key) { return this.poi[key]; }
public void POIList()
{
foreach (string line in File.ReadLines("POIList.txt"))
{
string[] parts = line.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
poi.Add(parts[0], new List<string>());
poi[parts[0]] = new List<string>(parts.Skip(1));
}
}
}
in the form1.cs
private void button1_Click(object sender, EventArgs e)
{
JSON_Output Json = new JSON_Output();
Json.ToJsonForLocation(comboBox1.Text);
}
also I set selectedindexchange from combobox2
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem != null)
{
POI poi1 = new POI();
poi1.POIList();
string txt = comboBox1.SelectedItem.ToString();
if (poi1.ContainsKey(txt))
{
List<string> points = poi1.GetValue(txt);
comboBox2.Items.Clear();
comboBox2.Items.AddRange(points.ToArray());
}
}
}
now where the json file generated to sore the value is-
public void ToJsonForLocation(string name)
{
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "Text_ImageWithHash");
string SubfolderName = Path.Combine(folderName, name);
//string folderName = Path.Combine(startPath, "Text_ImageWithHash");
System.IO.Directory.CreateDirectory(SubfolderName);
string fileName = name + ".json";
var path = Path.Combine(SubfolderName, fileName);
var Jpeg_File = new DirectoryInfo(startPath + #"\Image\" + name).GetFiles("*.jpg");
POIData Poi=new POIData();
Poi.Shorttext = File.ReadAllText(startPath + #"\Short Text\" + name + ".txt");
Poi.GeoCoordinates=GeosFromString(startPath + #"\Latitude Longitude\" + name + ".txt");
Poi.Images=new List<string> { Jpeg_File[0].Name};
string json = JsonConvert.SerializeObject(Poi,Formatting.Indented);
File.WriteAllText(path , json);
}
This is my code output while running the program.
after clicking button 1 Text_image_withHash folder is generated in the configuration directory.
Now if I open the folder I can see fthe following folders which is the key value from text file
After enable button 2 for combobox two the values folder is generated but not in the key folder.but as usual way in the Text_Image_withHash.
But What I want to do is-
To create that kind of folder-structure, simply use a foreach-loop. And String.Split.
Required usings:
using System;
using System.IO;
using System.Text;
using System.Linq;
Example:
// basePath can be anything
var basePath = "C:\Something";
// assume "info" is your CSV.
var infoParts = info.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (infoParts.Length == 0)
{
return;
}
var rootPath = infoParts[0];
Directory.CreateDirectory(Path.Combine(basePath, rootPath));
foreach (var subPath in infoParts.Skip(1))
{
Directory.CreateDirectory(Path.Combine(basePath, rootPath, subPath));
}
Saving JSON-files into these directories could then simply be made by combining the paths in a similar fashion.
I would also suggest some sanitizing of your paths (such as replacing '/' and '\\' with '_' or '-'.
Example implementation:
public void POIList()
{
foreach (string line in File.ReadLines("POIList.txt"))
{
string[] parts = line.Split(new[] { ';' },
StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0)
{
// Empty line or similar.
continue;
}
string cityName = parts[0];
poi.Add(cityName, new List<string>());
// Add the points of interest to local.
var points = new List<string>(parts.Skip(1));
poi[cityName] = points;
// basePath will have to be retrieved somehow. It's up to you.
string cityDirectoryPath = Path.Combine(basePath, cityName));
// Create a directory for the city.
Directory.CreateDirectory(cityDirectoryPath);
// Create sub-directories for points.
foreach (string point in points)
{
Directory.CreateDirectory(Path.Combine(
cityDirectoryPath, point));
}
}
}
I have just got my answer. This is the solution of the above question.
For POI Class :
public class POI
{
Dictionary<string, List<string>> poi = new Dictionary<string, List<string>>();
public bool ContainsKey(string key) { return this.poi.ContainsKey(key); }
public List<string> GetValue(string key) { return this.poi[key]; }
public void POIList()
{
foreach (string line in File.ReadLines("POIList.txt"))
{
string[] parts = line.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0)
{
// Empty line or similar.
continue;
}
string cityName = parts[0];
poi.Add(cityName, new List<string>());
// Add the points of interest to local.
var points = new List<string>(parts.Skip(1));
poi[cityName] = points;
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "FinalJson");
string cityDirectoryPath = Path.Combine(folderName, cityName);
Directory.CreateDirectory(cityDirectoryPath);
}
}
}
the the json output class
public void ToJsonForLocation(string CityName,string PoiName)
{
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "FinalJson");
string SubfolderName = Path.Combine(folderName, CityName);
System.IO.Directory.CreateDirectory(SubfolderName);
string fileName = PoiName + ".json";
var path = Path.Combine(SubfolderName, fileName);
var Jpeg_File = new DirectoryInfo(startPath + #"\Image\" + PoiName).GetFiles("*.jpg");
POIData Poi=new POIData();
Poi.Shorttext = File.ReadAllText(startPath + #"\Short Text\" + PoiName + ".txt");
Poi.GeoCoordinates = GeosFromString(startPath + #"\Latitude Longitude\" + PoiName + ".txt");
Poi.Images=new List<string> { Jpeg_File[0].Name};
string json = JsonConvert.SerializeObject(Poi,Formatting.Indented);
File.WriteAllText(path,json);
}
this is generated folder and file in this way-
The Final json file for all values

Properly parsing strings line by line from a website

I have this being echo into a blank page:
echo "Testing|Testing1|Testing2|Testing3|Testing4<br/>";
echo "Something|Something1|Something2|Something3|Something4";
Now I have a listview. In this example it would create 2 rows with 5 columns. So my question is, how to read line by line to properly create the number of rows that are displayed on the website?
Here's my code so far:
WebClient client = new WebClient();
string downloadString = client.DownloadString("https://example.com/Testing.php");
string[] downloadString2 = downloadString.Split(
new char[]
{
(char)'|'
}, System.StringSplitOptions.RemoveEmptyEntries);
ListViewItem item = new ListViewItem(
new[]
{
downloadString2[0].ToString(),
downloadString2[1].ToString(),
downloadString2[2].ToString(),
downloadString2[3].ToString(),
downloadString2[4].ToString()
});
listView1.Items.Add(item);
(The columns are already created in the listview)
--
Edit: This worked fine for me:
WebClient client = new WebClient();
string downloadString = client.DownloadString("https://example.com/Testing.php");
string[] stringSeparators = new string[] { "<br/>" };
string[] Lines = downloadString.Split(stringSeparators, StringSplitOptions.None);
string[] things = new string[5]; // Fixed size. I might find a way later to make it dynamically
int i = 0;
foreach (string line in Lines)
{
string[] words = line.Split('|');
i = 0;
foreach (string word in words)
{
things[i] = word;
i++;
}
ListViewItem item = new ListViewItem(
new[]
{
things[0],
things[1],
things[2],
things[3],
things[4]
});
listView1.Items.Add(item);
}
not exactly what you want but you can try this
WebClient client = new WebClient();
string downloadString = client.DownloadString("https://example.com/Testing.php");
string[] stringSeparators = new string[] {"<br/>"};
string[] Lines = downloadString.Split(stringSeparators, StringSplitOptions.None);
foreach (string line in Lines)
{
string[] words = line.Split('|');
foreach (string word in words)
{
ListViewItem item = new ListViewItem();
item.add(word);
}
listView1.Items.Add(item);
}

Categories

Resources