c# add textfile to 2 dimensional array - c#

I'm trying to read a text file, which contains proxys into a 2 dimensional array.
The text file looks like the following:
00.00.00.00:80
00.00.00.00:80
00.00.00.00:80
00.00.00.00:80
00.00.00.00:80
How could I seperate the ip from the port?`
So my array would look like the following:
[00.00.00.00][80]
Current code:
public void readProxyList(string FileName)
{
using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
string text = sr.ReadToEnd();
string[] lines = text.Split('\r');
foreach (string s in lines)
{
}
}
}

If you are not expecting the file to be too large you could use File.ReadAllLines to read in each line. Then to split, just use String.Split with ':' as your token.
Example:
var lines = File.ReadAllLines(FileName));
var array = new string[lines.Length,2];
for(int i=0; i < lines.Length; i++)
{
var temp = lines[i].Split(':');
array[i,0] = temp[0];
array[i,1] = temp[1];
}
Edit
If you expect that the file may be large, instead of using ReadAllLines you can use File.ReadLines. This method returns an IEnumerable<string> and will not read the whole file at once. In this case, I would probably opt away from the 2d array and make a simple class (call it IpAndPort or something like that) and create a list of those.
Example:
public sealed class IpAndPort
{
public string Ip { get; private set; }
public string Port { get; private set; }
public IpAndPort (string ip, string port)
{
Ip = ip;
Port = port;
}
}
var list = new List<IpAndPort>();
foreach(var line in File.ReadLines(FileName))
{
var temp = line.Split(':');
list.Add(new IpAndPort(temp[0], temp[1]);
}

Try this:
public IEnumerable<string> GetProxyList(string FileName)
{
string[] allLines = File.ReadAllLines(FileName);
var result = new List<string>(allLines.Length);
foreach (string line in allLines)
{
var splittedLine = line.Split(':');
result.Add($"[{splittedLine[0]}][{splittedLine[1]}]");
}
return result;
}

Related

C# How to implement CSV file into this code

Hi I am fairly new to coding, I have a piece of code that searches for a string and replaces it with another string like so:
var replacements = new[]{
new{Find="123",Replace="Word one"},
new{Find="ABC",Replace="Word two"},
new{Find="999",Replace="Word two"},
};
var myLongString = "123 is a long 999 string yeah";
foreach(var set in replacements)
{
myLongString = myLongString.Replace(set.Find, set.Replace);
}
If I want to use a CSV file that contains a lot of words and their replacements, for example, LOL,Laugh Out Loud, and ROFL, Roll Around Floor Laughing. How would I implement that?
Create a text file that looks like (you could use commas, but I like pipes (|)):
123|Word One
ABC|Word Two
999|Word Three
LOL|Laugh Out Loud
ROFL|Roll Around Floor Laughing
Then create a tiny helper class:
public class WordReplace
{
public string Find { get; set; }
public string Replace { get; set; }
}
And finally, call this code:
private static string DoWordReplace()
{
//first read in the data
var fileData = File.ReadAllLines("WordReplace.txt");
var wordReplacePairs = new List<WordReplace>();
var lineNo = 1;
foreach (var item in fileData)
{
var pair = item.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
if (pair.Length != 2)
{
throw new ApplicationException($"Malformed file, line {lineNo}, data = [{item}] ");
}
wordReplacePairs.Add(new WordReplace{Find = pair[0], Replace = pair[1]});
++lineNo;
}
var longString = "LOL, 123 is a long 999 string yeah, ROFL";
//now do the replacements
var buffer = new StringBuilder(longString);
foreach (var pair in wordReplacePairs)
{
buffer.Replace(pair.Find, pair.Replace);
}
return buffer.ToString();
}
The result is:
Laugh Out Loud, Word One is a long Word Three string yeah, Roll Around Floor Laughing

How to split string containing multiple delimeters of each and every line of text file?

This is the Input my file contains:
50|Hallogen|Mercury|M:4;C:40;A:1
90|Oxygen|Mars|M:10;C:20;A:00
5|Hydrogen|Saturn|M:33;C:00;A:3
Now i want to split each and every line of my text file and store in my class file like :
Expected output:
Planets[0]:
{
Number:50
name: Hallogen
object:Mercury
proportion[0]:
{
Number:4
},
proportion[1]:
{
Number:40
},
proportion[2]:
{
Number:1
}
}
etc........
My class file to store all this values:
public class Planets
{
public int Number { get; set; } //This field points to first cell of every row.output 50,90,5
public string name { get; set; } //This field points to Second cell of every row.output Hallogen,Oxygen,Hydrogen
public string object { get; set; } ////This field points to third cell of every row.output Mercury,Mars,Saturn
public List<proportion> proportion { get; set; } //This will store all proportions with respect to planet object.
//for Hallogen it will store 4,40,1.Just store number.ignore M,C,A initials.
//for oxygen it will store 10,20,00.Just store number.ignore M,C,A initials.
}
public class proportion
{
public int Number { get; set; }
}
This is what i have done:
List<Planets> Planets = new List<Planets>();
using (StreamReader sr = new StreamReader(args[0]))
{
String line;
while ((line = sr.ReadLine()) != null)
{
string[] parts = Regex.Split(line, #"(?<=[|;-])");
foreach (var item in parts)
{
var Obj = new Planets();//Not getting how to store it but not getting proper output in parts
}
Console.WriteLine(line);
}
}
Without you having to change any of your logic in "Planets"-class my fast solution to your problem would look like this:
List<Planets> Planets = new List<Planets>();
using (StreamReader sr = new StreamReader(args[0]))
{
String line;
while ((line = sr.ReadLine()) != null)
{
Planets planet = new Planets();
String[] parts = line.Split('|');
planet.Number = Convert.ToInt32(parts[0]);
planet.name = parts[1];
planet.obj = parts[2];
String[] smallerParts = parts[3].Split(';');
planet.proportion = new List<proportion>();
foreach (var item in smallerParts)
{
proportion prop = new proportion();
prop.Number =
Convert.ToInt32(item.Split(':')[1]);
planet.proportion.Add(prop);
}
Planets.Add(planet);
}
}
Oh before i forget it, you should not name your property of class Planets "object" because "object" is a keyword for the base class of everything, use something like "obj", "myObject" ,"planetObject" just not "object" your compiler will tell you the same ;)
To my understanding, multiple delimiters are maintained to have a nested structure.
You need to split the whole string first based on pipe, followed by semi colon and lastly by colon.
The order of splitting here is important. I don't think you can have all the tokens at once by splitting with all 3 delimiters.
Try following code for same kind of data
var values = new List<string>
{
"50|Hallogen|Mercury|M:4;C:40;A:1",
"90|Oxygen|Mars|M:10;C:20;A:00",
"5|Hydrogen|Saturn|M:33;C:00;A:3"
};
foreach (var value in values)
{
var pipeSplitted = value.Split('|');
var firstNumber = pipeSplitted[0];
var name = pipeSplitted[1];
var objectName = pipeSplitted[2];
var semiSpltted = value.Split(';');
var secondNumber = semiSpltted[0].Split(':')[1];
var thirdNumber = semiSpltted[1].Split(':')[1];
var colenSplitted = value.Split(':');
var lastNumber = colenSplitted[colenSplitted.Length - 1];
}
The most straigtforward solution is to use a regex where every (sub)field is matched inside a group
var subjectString = #"50|Hallogen|Mercury|M:4;C:40;A:1
90|Oxygen|Mars|M:10;C:20;A:00
5|Hydrogen|Saturn|M:33;C:00;A:3";
Regex regexObj = new Regex(#"^(.*?)\|(.*?)\|(.*?)\|M:(.*?);C:(.*?);A:(.*?)$", RegexOptions.Multiline);
Match match = regexObj.Match(subjectString);
while (match.Success) {
match.Groups[1].Value.Dump();
match.Groups[2].Value.Dump();
match.Groups[3].Value.Dump();
match.Groups[4].Value.Dump();
match.Groups[5].Value.Dump();
match.Groups[6].Value.Dump();
match = match.NextMatch();
}
If I understand correctly, your input is well formed. In this case you could use something like this:
string[] parts = Regex.Split(line, #"[|;-]");
var planet = new Planets(parts);
...
public Planets(string[] parts) {
int.TryParse(parts[0], this.Number);
this.name = parts[1];
this.object = parts[2];
this.proportion = new List<proportion>();
Regex PropRegex = new Regex("\d+");
for(int i = 3; i < parts.Length; i++){
Match PropMatch = PropRegex.Match(part[i]);
if(PropMatch.IsMatch){
this.proportion.Add(int.Parse(PropMatch.Value));
}
}
}

Separate string from list C#

I have list of string and each of that strings in list look like this: sim_pin: 1234. List have 24 strings, and I wanna to get each of that strings, separate string where separator will be : ( : and space), and save to list only that part who is right from separator.
EDIT:
Here is my code
string url = #"E:\Sims.log";
public static IEnumerable<DiverGate> GetData(string url)
{
Stream stream = File.Open(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamReader sr = new StreamReader(stream))
{
string str = sr.ReadToEnd();
string[] lines = Regex.Split(str, "\r\n");
List<string> lista = new List<string>();
foreach (string line in lines)
{
lista.Add(line);
}
List<string> header = lista.GetRange(0, 23);
//I stop here and im out of idea
}
}
Something like this should work:
where input is your original list of strings
List<string> output = new List<string>();
input.ForEach(x=> output.Add(x.Split(new[] {": "},StringSplitOptions.None).Last()));
var List1 = new List<string>{"sim_pin: 1234", "sim_pin: 2345", "sim_pin: 3456"};
var List2 = new List<string>();
foreach (var s in List1) {
var ns = s.Split(':')[1].TrimStart(' ');
List2.Add(ns);
}
try this code:
for ( int i =0; i< yourList.Count(); i++) {
string s = yourList[i];
int i = s.indexOf(":");
s = s.Substring (i);
yourList.Insert(i, s);
}

C# Parse CSV to JSON Wrong Format

Take a look and let me know what the hell i'm derping on ;)
[HttpPost]
public ActionResult Upload(HttpPostedFileBase File)
{
HttpPostedFileBase csvFile = Request.Files["adGroupCSV"];
byte[] buffer = new byte[csvFile.ContentLength];
csvFile.InputStream.Read(buffer, 0, csvFile.ContentLength);
string csvString = System.Text.Encoding.UTF8.GetString(buffer);
string[] lines = Regex.Split(csvString, "\r");
List<string[]> csv = new List<string[]>();
foreach (string line in lines)
{
csv.Add(line.Split(','));
}
string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(csv);
ViewData["CSV"] = json;
return View(ViewData);
}
This is how it is coming across:
json = "[[\"Col1\",\"Col2\",\"Col3\",\"Col4\",\"Col5\",\"Col6\"],[\"test\",\"test\",\"test\",\"test\",\"http://www.test.com/\",\"test/\"],[\"test\",\"test\",\"test\",\"test\",\"http://www.test.com...
This is how I want it:
{"Col1":"test","Col2":"test","Col3":"test","Col4":"test","Col5":"http://www.test.com/","Col6":"test/"}
Here is an example of the CSV
Col1,Col2,Col3,Col4,Col5,Col6
Test1,Test1,Test1,test1,test.test,test/
Test2,Test2,Test2,test2,test.test,test/
Test3,Test3,Test3,test3,test.test,test/
Test4,Test4,Test4,test4,test.test,test/
You need a dictionary. Just replace
List<string[]> csv = new List<string[]>();
foreach (string line in lines)
{
csv.Add(line.Split(','));
}
with
var csv = lines.Select(l => l.Split(',')
.Select((s,i)=>new {s,i})
.ToDictionary(x=>"Col" + (x.i+1), x=>x.s));
It should work...
EDIT
var lines = csvString.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
var cols = lines[0].Split(',');
var csv = lines.Skip(1)
.Select(l => l.Split(',')
.Select((s, i) => new {s,i})
.ToDictionary(x=>cols[x.i],x=>x.s));
var json = new JavaScriptSerializer().Serialize(csv);
It looks like you have a an array of string arrays when you just want one object with all your columns as properties on it.
Instead of building up your
List<string[]> csv = new List<string[]>();
Can you make a new object from your JSON, like this:
public class UploadedFileObject
{
public string Col1 { get; set; }
public string Col2 { get; set; }
public string Col3 { get; set; }
public string Col4 { get; set; }
public string Col5 { get; set; }
public string Col6 { get; set; }
}
[HttpPost] public ActionResult Upload(HttpPostedFileBase File)
{
HttpPostedFileBase csvFile = Request.Files["adGroupCSV"];
byte[] buffer = new byte[csvFile.ContentLength];
csvFile.InputStream.Read(buffer, 0, csvFile.ContentLength);
string csvString = System.Text.Encoding.UTF8.GetString(buffer);
string[] lines = Regex.Split(csvString, "\r");
List<UploadedFileObject> returnObject = new List<UploadedFileObject>();
foreach (string line in lines)
{
String[] lineParts = line.Split(',');
UploadedFileObject lineObject = new UploadedFileObject();
lineObject.Col1 = lineParts[0];
lineObject.Col2 = lineParts[1];
lineObject.Col3 = lineParts[2];
lineObject.Col4 = lineParts[3];
lineObject.Col5 = lineParts[4];
lineObject.Col6 = lineParts[5];
returnObject.add(lineObject);
}
string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(returnObject);
ViewData["CSV"] = json;
return View(ViewData);
}
In line with the previous answer, perhaps you could use ServiceStack to deserialize the CSV into an array of objects, then re-serialize it using ServiceStack's JSON serializer?
http://www.servicestack.net/docs/text-serializers/json-csv-jsv-serializers
You need to ensure you are using the format that the JavaScriptSerializer expects you to.
Since you are giving it a List<string[]> it is formatting it as:
"[[list1Item1,list1Item2...],[list2Item1,list2Item2...]]"
Which would correlate in your file as row1 -> list1 etc.
However what you want is the first item from the first list, lining up with the first item in the second list and so on.
I don't know about the exact workings of JavaScriptSerializer, but you could try giving it a Dictionary instead of a List<string[]>, assuming you only had one line of data (two lines total).
This would involve caching the first two lines and doing the following:
for (int i = 0; i < first.Length; i++)
{
dict.Add(first[i],second[i]);
}

C# split textfile into a 2 dimensional string array

I have a textfile that looks like this :
John,Gauthier,blue,May
Henry,Ford,Red,June
James,Bond,Orange,December
I want to split it into a two dimensional string array so I could separate each lines then each words. Ex:
mystring[0][0] = "John"
mystring[1][3] = "June"
mystring[2][2] = "Orange"
Here's what I did right now:
string[] words = new string [100];
System.IO.StreamReader myfile = new System.IO.StreamReader("c:\\myfile.csv");
while (fichier.Peek() != -1)
{
i++;
words = myfile.ReadLine().Split(',');
}
I'm stuck. I'm able to split it into a one dimensional string array but not into a two dimensional string array. I guess I need to split it two times ; First time with '\n' and the second time with ',' and then put those two together.
This is actually a one-liner:
File.ReadLines("myfilename.txt").Select(s=>s.Split(',')).ToArray()
Since this is a beginner question, here's what's going on:
File.ReadLines(filename) returns a collection of all lines in your text file
.Select is an extension method that takes a function
s=>s.Split(',') is the function, it splits the string s by all commas and returns an array of strings.
.ToArray() takes the collection of string arrays created by .Select and makes an array out of that, so you get array of arrays.
Try this
var str = File.ReadAllText("myfile.csv");
var arr = str.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
var multi = arr.Select(x => x.Split(',')).ToArray();
Try:
var First = new string [100];
var Sec = new string [100];
System.IO.StreamReader myfile = new System.IO.StreamReader("c:\\myfile.csv");
while (fichier.Peek() != -1)
{
i++;
var buff = myfile.ReadLine().Split(',');
First[i] = buff[0];
Sec[i] = buff[1];
}
Other idea, use a XML serilizer to serilize your hole Object. Two extensions for this:
public static void SaveAsXML(this Object A, string FileName)
{
var serializer = new XmlSerializer(A.GetType());
using (var textWriter = new StreamWriter(FileName))
{
serializer.Serialize(textWriter, A);
textWriter.Close();
}
}
public static void LoadFromXML(this Object A, string FileName)
{
if (File.Exists(FileName))
{
using (TextReader textReader = new StreamReader(FileName))
{
XmlSerializer deserializer = new XmlSerializer(A.GetType());
A = (deserializer.Deserialize(textReader));
}
}
}
Add than in any Static class and call:
YourSaveClassWhitchContainsYourArray.SaveAsXML("Datastore.xml");
or
YourSaveClassWhitchContainsYourArray.LoadFromXML("Datastore.xml");

Categories

Resources