Loading entries from a list made from .csv file - c#

I am trying to retrieve data from a series of lists that have been populated from a single .csv file
i have the entire list added to a Dictionary and abbreviations from "lol" speak
so far i have it able to search through the list/dictionary and determine whether the item that is searched for is present or not. All i want to do it to write the:
abbreviation - full meaning
into the console
Here is my code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace expanded_meanings
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> lolspeak_dictionary = new Dictionary<string, string>();
var reader = new StreamReader(File.OpenRead(#"H:\twitter.csv"));
List<string> short_name = new List<string>();
List<string> longer_name = new List<string>();
int count=0;
string search = Console.ReadLine();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
lolspeak.Add(values[0], values[1]);
short_name.Add(values[0]);
longer_name.Add(values[1]);
count = count + 1;
}
if (short_name.Contains(search))
{
Console.WriteLine("Item found");
}
else
Console.WriteLine("Not Found");
Console.ReadLine();
}
//if (short_name = user_search);
}
}

First, you do not need the short_name and long_name as those values are contained within the lolspeak_dictionary, You can access them by using the Keys and Values properties of a Dictionary.
As for searching for the abbreviation - full meaning you can simply use your current code as
if (lolspeak_dictionary.ContainsKey(search))
{
Console.WriteLine("{0} - {1}", search, lolspeak_dictionary[search]);
}
else {
Console.WriteLine("'{0}' - Not Found", search);
}
UPDATE:
The method call Console.WriteLine("'{0}' - Not Found", search); works by using substitution. The value of search, is placed in the spot of {0}. The means that {0} - Not Found if search is WOTR you will get WOTR - Not found.
In the case of Console.WriteLine("{0} - {1}", search, lolspeak_dictionary[search]);. If search is WOTA, you would get WOTA - Will of the Ancients.
Additional Resources
Dictionary MSDN
Keys MSDN
Values MSDN
Understanding Dictionary

Related

Can I sort date in a csv text document with a button?

I'm trying to sort the dates in the csv that is saved in my text document with following format:
EventName1, EventType1, 05-06-2019, Location1, Details1
EventName2, EventType2, 05-06-2019, Location2, Details2
EventName3, EventType3, 05-06-2019, Location3, Details3
and so on.
The sort will be done by a button, and will be viewed on a listview.
I have successfully completed sorting by letter, and showing on the listview.
//SORTS THE DATA IN ASCENDING ORDER
string inFile = #"Events.txt";
var contents = File.ReadAllLines(inFile);
Array.Sort(contents);
File.WriteAllLines(inFile, contents);
//CLEARS EVERYTHING IN THE LISTVIEW
listView1.Items.Clear();
//OPENS THE DATA AGAIN IN THE LISTVIEW AFTER BEING SORTED
foreach (var line in System.IO.File.ReadLines(#"Events.txt"))
{
// Split only the single line
string[] lineItems = line.Split(',');
ListViewItem listView1 = new ListViewItem();
listView1.Text = lineItems[0];
listView1.SubItems.Add(lineItems[1]);
listView1.SubItems.Add(lineItems[2]);
listView1.SubItems.Add(lineItems[3]);
listView1.SubItems.Add(lineItems[4]);
this.listView1.Items.Add(listView1);
}
I have tried doing this but for the dates, and I haven't got far. I'm trying to sort dates from first to last, but I can't figure out the code.
Try to add the date column that you will OrderBy and then use DateTime.Parse
you can see these examples 1 2
You can run the code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] contents = File.ReadAllLines(#"f.txt");
var sorted = contents.Select(line => new
{// Make sure that you use the index depend on your line
SortKey = DateTime.Parse(line.Split(',')[2]),
Line = line
}
).OrderBy(x => x.SortKey).ToList();
sorted.ForEach(Console.WriteLine);
}
}
}
You can use Linq to sort your csv file like below(make sure you have a using for System.Linq):
var orderedCsv = File.ReadLines(#"Events.txt")
.OrderBy(f => f.Split(',')[2]).ToList();
You read in your lines and then using order by with the field you want which is the 2nd in the 0 based split you can push to a list. Then you can loop through the ordered csv and add it to your listview
foreach (var line in orderedCsv)
{
// Split only the single line
var lineItems = line.Split(',');
var listView1 = new ListViewItem {Text = lineItems[0]};
listView1.SubItems.Add(lineItems[1]);
listView1.SubItems.Add(lineItems[2]);
listView1.SubItems.Add(lineItems[3]);
listView1.SubItems.Add(lineItems[4]);
listView1.Items.Add(listView1);
}

How to write and read list to text file that contains user input using c#

I am working on Console Application and I am trying to save list to txt file and read that data later.
In program user inputs name of category and I am not sure how to save that with list in txt file.
Struct Category that holds name.
struct Category
{
public string name;
}
This is my code so far.
Category k;
Console.WriteLine("Enter name of category: ");
k.name = Console.ReadLine();
List<String> category = new List<string>();
TextWriter tw = new StreamWriter("../../dat.txt");
foreach (string k in category)
{
string[] en = s.Split(',');
category.Add(k.name); // Here I am not sure how to save name
}
tw.Close();
StreamReader sr = new StreamReader("../../dat.txt");
string data = sr.ReadLine();
while (data != null)
{
Console.WriteLine(data);
data = sr.ReadLine();
}
sr.Close();
It doesn't give me any error but it's not writing name to txt file.
SOLUTIN
string filePath = #"../../datoteka.txt";
List<String> kategorije = File.ReadAllLines(filePath).ToList();
foreach (string s in kategorije)
{
Console.WriteLine(s);
}
kategorije.Add(k.naziv);
File.WriteAllLines(filePath,kategorije);
You can use the static methods of the System.IO.File class. Their advantage is that they open and close files automatically, thus reducing the task of writing and reading files to a single statement
File.WriteAllLines(yourFilePath, category);
You can read the lines back into a list with
 category = new List(ReadLines(yourFilePath));
ReadLines returns an IEnumerable<string> that is accepted as data source in the constructor of the list.
or into an array with
string[] array = ReadAllLines(yourFilePath);
Your solution does not write anything to the output stream. You are initializing a TextWriter but not using it. You would use it like
tw.WriteLine(someString);
Your code has some problems: You are declaring a category variable k, but you never assign it a category. Your list is not of type category.
A better solution would work like this
var categories = new List<Category>(); // Create a categories list.
while (true) { // Loop as long as the user enters some category name.
Console.WriteLine("Enter name of category: ");
string s = Console.ReadLine(); // Read user entry.
if (String.IsNullOrWhiteSpace(s)) {
// No more entries - exit loop
break;
}
// Create a new category and assign it the entered name.
var category = new Category { name = s };
//TODO: Prompt the user for more properties of the category and assign them to the
// category.
// Add the category to the list.
categories.Add(category);
}
File.WriteAllLines(yourFilePath, categories.Select(c => c.name));
The Category type should be class. See: When should I use a struct instead of a class?
You are not using WtiteLine to write content. Add below code in your solution after
category.Add(k.name);
tw.WriteLine(someString);
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file
Find below sample code for read and write.
class WriteTextFile
{
static void Main()
{
System.IO.File.WriteAllLines(#"C:\Users\Public\TestFolder\WriteLines.txt", lines);
string text = "A class is the most powerful data type in C#. Like a structure, " +
"a class defines the data and behavior of the data type. ";
System.IO.File.WriteAllText(#"C:\Users\Public\TestFolder\WriteText.txt", text);
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\Public\TestFolder\WriteLines2.txt"))
{
foreach (string line in lines)
{
if (!line.Contains("Second"))
{
file.WriteLine(line);
}
}
}
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\Public\TestFolder\WriteLines2.txt", true))
{
file.WriteLine("Fourth line");
}
}
}

Searching a list C#

Hope all is well.
I am struggling with a simple problem here. I am trying to create a console app that allows you to search for words in a list (by one or more characters ie u = user, user group).
I can't seem to get past this error:
Error CS0305 Using the generic type 'List' requires 1 type arguments wordSearch c:\Projects\wordSearch\wordSearch\Program.cs 36 Active
Please find my code below..... Any help is welcome Thank you in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace wordSearch
{
public class MyList<T> { }
public class TestList<T> { }
class MyList
{
public static void Main()
{
string searchKeyword = "o";
List<string> items = new List<string>();
items.Add("User");
items.Add("User Groups");
items.Add("User Activity Log");
items.Add("Report Designer");
items.Add("Report Activity Log");
List<string> searchResults = items.FindAll(u =>
u.Contains(searchKeyword));
Console.WriteLine("Please type in the first letter of item you
are looking for:");
Console.ReadLine();
foreach (var result in System.Collections.Generic.List.Where(u =>
u.IndexOf(mySearchString) == 0))
{
Console.WriteLine("User, User Groups, User Activity Log");
Console.ReadKey();
}
foreach (var result in List.Where(r => r.IndexOf(mySearchString) ==
0))
{
Console.WriteLine("Report Desinger, Report Activity Log");
Console.ReadKey();
}
}
}
}
There are two issues with your code:
You have to save user's input ("...the first letter user is looking for..."), e.g. in mySearchString which you've already used as filter.
You have to query and scan items instance, not System.Collections.Generic.ListList type:
You can put it like this:
...
Console.WriteLine("Please type in the first letter of item you are looking for:");
//DONE: user input saved
string mySearchString = Console.ReadLine();
//DONE: we scan items, not List
foreach (var result in items.Where(u => u.IndexOf(mySearchString) == 0)) {
Console.WriteLine("User, User Groups, User Activity Log");
Console.ReadKey();
}
// DONE: we scan items not List
foreach (var result in items.Where(r => r.IndexOf(mySearchString) == 0)) {
Console.WriteLine("Report Desinger, Report Activity Log");
Console.ReadKey();
}
...
Edit: It seems that the actual request is to query list in a loop, foreach not copy-pasting, something like this:
public static void Main() {
List<string> items = new List<string>() {
"User",
"User Groups",
"User Activity Log",
"Report Designer",
"Report Activity Log",
}
while (true) {
Console.WriteLine("Please type in the first letter of item you are looking for:");
Console.WriteLine("Prease press enter (i.e. type an empty string) to quit");
string mySearchString = Console.ReadLine();
if (string.IsNullOrEmpty(mySearchString))
break;
foreach (var item in items.Where(r => r.IndexOf(mySearchString) == 0))
Console.WriteLine(item);
Console.WriteLine();
}
}

C# Comparing an Input to a String Exactly

I have a list of most of the elements in the periodic table in order of their placement on the table:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chemistry_Element_Calculator
{
class Program
{
static void Main(string[] args)
{
// Declare all numbers
int electronNumber;
int protonNumber;
float neutronNumber;
int i;
// Declare all strings
string elementRequest;
// Create an list for all elements
List<string> elementNameList = new List<string>();
List<string> elementSymbolList = new List<string>();
// Add all elements to the list
elementNameList.Add("Hydrogen"); elementSymbolList.Add("H");
elementNameList.Add("Helium"); elementSymbolList.Add("He");
elementNameList.Add("Lithium"); elementSymbolList.Add("Li");
elementNameList.Add("Beryllium"); elementSymbolList.Add("Be");
elementNameList.Add("Boron"); elementSymbolList.Add("B");
elementNameList.Add("Carbon"); elementSymbolList.Add("C");
elementNameList.Add("Nitrogen"); elementSymbolList.Add("N");
elementNameList.Add("Oxygen"); elementSymbolList.Add("O");
elementNameList.Add("Fluorine"); elementSymbolList.Add("F");
elementNameList.Add("Neon"); elementSymbolList.Add("Ne");
elementNameList.Add("Sodium"); elementSymbolList.Add("Na");
elementNameList.Add("Magnesium"); elementSymbolList.Add("Mg");
elementNameList.Add("Aluminium"); elementSymbolList.Add("Al");
elementNameList.Add("Silicon"); elementSymbolList.Add("Si");
elementNameList.Add("Phosphorus"); elementSymbolList.Add("P");
elementNameList.Add("Sulfur"); elementSymbolList.Add("S");
elementNameList.Add("Chlorine"); elementSymbolList.Add("Cl");
elementNameList.Add("Argon"); elementSymbolList.Add("Ar");
elementNameList.Add("Potassium"); elementSymbolList.Add("K");
elementNameList.Add("Calcium"); elementSymbolList.Add("Ca");
elementNameList.Add("Scandium"); elementSymbolList.Add("Sc");
elementNameList.Add("Titanium"); elementSymbolList.Add("Ti");
elementNameList.Add("Vanadium"); elementSymbolList.Add("V");
elementNameList.Add("Chromium"); elementSymbolList.Add("Cr");
elementNameList.Add("Manganese"); elementSymbolList.Add("Mn");
elementNameList.Add("Iron"); elementSymbolList.Add("Fe");
elementNameList.Add("Cobalt"); elementSymbolList.Add("Co");
elementNameList.Add("Nickel"); elementSymbolList.Add("Ni");
elementNameList.Add("Copper"); elementSymbolList.Add("Cu");
elementNameList.Add("Zinc"); elementSymbolList.Add("Zn");
elementNameList.Add("Gallium"); elementSymbolList.Add("Ga");
elementNameList.Add("Germanium"); elementSymbolList.Add("Ge");
elementNameList.Add("Arsenic"); elementSymbolList.Add("As");
elementNameList.Add("Selenium"); elementSymbolList.Add("Se");
elementNameList.Add("Bromine"); elementSymbolList.Add("Br");
elementNameList.Add("Krypton"); elementSymbolList.Add("Kr");
elementNameList.Add("Rubidium"); elementSymbolList.Add("Rb");
elementNameList.Add("Strontium"); elementSymbolList.Add("Sr");
elementNameList.Add("Yttrium"); elementSymbolList.Add("Y");
elementNameList.Add("Zirconium"); elementSymbolList.Add("Zr");
elementNameList.Add("Niobium"); elementSymbolList.Add("Nb");
elementNameList.Add("Molybdenum"); elementSymbolList.Add("Mo");
elementNameList.Add("Technetium"); elementSymbolList.Add("Tc");
elementNameList.Add("Rubidium"); elementSymbolList.Add("Ru");
elementNameList.Add("Rhodium"); elementSymbolList.Add("Rh");
elementNameList.Add("Palladium"); elementSymbolList.Add("Pd");
elementNameList.Add("Silver"); elementSymbolList.Add("Ag");
elementNameList.Add("Cadmium"); elementSymbolList.Add("Cd");
elementNameList.Add("Indium"); elementSymbolList.Add("In");
elementNameList.Add("Tin"); elementSymbolList.Add("Sn");
elementNameList.Add("Antimony"); elementSymbolList.Add("Sb");
elementNameList.Add("Tellurium"); elementSymbolList.Add("Te");
elementNameList.Add("Iodine"); elementSymbolList.Add("I");
elementNameList.Add("Xenon"); elementSymbolList.Add("Xe");
elementNameList.Add("Caesium"); elementSymbolList.Add("Cs");
elementNameList.Add("Barium"); elementSymbolList.Add("Ba");
elementNameList.Add("Lanthanum"); elementSymbolList.Add("La");
elementNameList.Add("Cerium"); elementSymbolList.Add("Ce");
elementNameList.Add("Praseodynium"); elementSymbolList.Add("Pr");
elementNameList.Add("Neodymium"); elementSymbolList.Add("Nd");
elementNameList.Add("Promethium"); elementSymbolList.Add("Pm");
elementNameList.Add("Samarium"); elementSymbolList.Add("Sm");
elementNameList.Add("Europium"); elementSymbolList.Add("Eu");
elementNameList.Add("Gadolinium"); elementSymbolList.Add("Gd");
elementNameList.Add("Terbium"); elementSymbolList.Add("Tb");
elementNameList.Add("Dysprosium"); elementSymbolList.Add("Dy");
elementNameList.Add("Holomium"); elementSymbolList.Add("Ho");
elementNameList.Add("Erbium"); elementSymbolList.Add("Er");
elementNameList.Add("Thulium"); elementSymbolList.Add("Tm");
elementNameList.Add("Ytterbium"); elementSymbolList.Add("Yb");
elementNameList.Add("Lutenium"); elementSymbolList.Add("Lu");
elementNameList.Add("Hafnium"); elementSymbolList.Add("Hf");
elementNameList.Add("Tantalum"); elementSymbolList.Add("Ta");
elementNameList.Add("Tungsten"); elementSymbolList.Add("W");
elementNameList.Add("Rhenium"); elementSymbolList.Add("Re");
elementNameList.Add("Osmium"); elementSymbolList.Add("Os");
elementNameList.Add("Iridium"); elementSymbolList.Add("Ir");
elementNameList.Add("Platinum"); elementSymbolList.Add("Pt");
elementNameList.Add("Gold"); elementSymbolList.Add("Au");
elementNameList.Add("Mercury"); elementSymbolList.Add("Hg");
elementNameList.Add("Thallium"); elementSymbolList.Add("Tl");
elementNameList.Add("Lead"); elementSymbolList.Add("Pb");
elementNameList.Add("Bismuth"); elementSymbolList.Add("Bi");
elementNameList.Add("Polonium"); elementSymbolList.Add("Po");
elementNameList.Add("Astatine"); elementSymbolList.Add("At");
elementNameList.Add("Radon"); elementSymbolList.Add("Rn");
elementNameList.Add("Francium"); elementSymbolList.Add("Fr");
elementNameList.Add("Radium"); elementSymbolList.Add("Ra");
elementNameList.Add("Actinium"); elementSymbolList.Add("Ac");
elementNameList.Add("Thorium"); elementSymbolList.Add("Th");
elementNameList.Add("Palladium"); elementSymbolList.Add("Pa");
elementNameList.Add("Uranium"); elementSymbolList.Add("U");
elementNameList.Add("Nepturium"); elementSymbolList.Add("Np");
elementNameList.Add("Plutonium"); elementSymbolList.Add("Pu");
elementNameList.Add("Americium"); elementSymbolList.Add("Am");
elementNameList.Add("Curium"); elementSymbolList.Add("Cm");
elementNameList.Add("Berkelium"); elementSymbolList.Add("Bk");
elementNameList.Add("Californium"); elementSymbolList.Add("Cf");
elementNameList.Add("Einsteinium"); elementSymbolList.Add("Es");
elementNameList.Add("Fermium"); elementSymbolList.Add("Fermium");
elementNameList.Add("Mendelevium"); elementSymbolList.Add("Md");
elementNameList.Add("Nobelium"); elementSymbolList.Add("No");
elementNameList.Add("Lawrencium"); elementSymbolList.Add("Lr");
elementNameList.Add("Rutherfordium"); elementSymbolList.Add("Rf");
elementNameList.Add("Dubnium"); elementSymbolList.Add("Db");
elementNameList.Add("Seaborgium"); elementSymbolList.Add("Sg");
elementNameList.Add("Bohrium"); elementSymbolList.Add("Bh");
elementNameList.Add("Hassium"); elementSymbolList.Add("Hs");
elementNameList.Add("Meitnerium"); elementSymbolList.Add("Mt");
elementNameList.Add("Darmstadtium"); elementSymbolList.Add("Ds");
elementNameList.Add("Roentgenium"); elementSymbolList.Add("Rg");
elementNameList.Add("Copernicium"); elementSymbolList.Add("Cn");
Console.WriteLine("What element do you want? Either input it's full name, with a capital letter, or it's elemnent symbol. E.g. N for Nitrogen");
elementRequest = Console.ReadLine();
elementNameList.ForEach(delegate (String elementName)
{
if (elementRequest == elementName)
{
Console.WriteLine("Hydrogen");
}
else
{
Console.WriteLine("Not Hydrogen");
};
});
Console.Read();
However, when I run the program, and input Hydrogen, both Helium and Hydrogen are said to be hydrogen. How can I fix this?
Also, if anyone has an idea on how to compress the 2 lists so they're smaller, let me know :)
Thanks :)
What you want your code to do is take the index from the first list, and return the string at the same index in the second list.
Your code is currently not doing any of that, but always printing "Hydrogen", your output thus always being "Hydrogen" whatever element is requested.
You can trivially fix that by actually looking up the index:
int indexOfElementName = elementNameList.IndexOf(elementRequest);
string elementSymbol = elementSymbolList[indexOfElementName];
Note that that does not handle casing and requested elements that aren't in the list (or typos).
But keeping the two lists in sync, and this code in general, is a maintenance disaster waiting to happen.
Instead you could use a dictionary where the element name is the key and the symbol the value:
var elementDictionary = new Dictionary<string, string>
{
{ "Hydrogen", "H" },
{ "Helium", "He" },
// ...
}
Then look it up:
string elementSymbol = elementDictionary[elementRequest];
Do note that this still doesn't handle case-insensitivity and elements that are not found, but I'll leave that as an exercise to you.
I would use a custom class and a list as suggested by ElectricRouge.
I don't favor the dictionary because you need to search both by name and symbol. Also, the data set is small (118 elements to date).
See comments for the explanation of the code.
using System;
using System.Collections.Generic;
namespace Chemistry_Element_Calculator
{
// Create a chemical element class
// You can add more properties such as number of electrons, etc.
public class ChemicalElement
{
public string Symbol
{
get; set;
}
public string Name
{
get; set;
}
}
class Program
{
static void Main(string[] args)
{
// Create a list of the elements, populate their properties
var elements = new List<ChemicalElement>()
{
new ChemicalElement {Name = "Hydrogen", Symbol = "H"},
new ChemicalElement {Name = "Helium", Symbol = "He"},
new ChemicalElement {Name = "Lithium", Symbol = "Li"}
// etc.
};
Console.WriteLine("What element do you want? Either input it's full name, with a capital letter, or it's elemnent symbol. E.g. N for Nitrogen");
var elementRequest = Console.ReadLine();
// Use find to get a matching element, compare both name and symbol
var foundElement = elements.Find(element => element.Symbol == elementRequest || element.Name == elementRequest);
if (foundElement == null)
{
// Output if no element is found
Console.WriteLine("Element Not Found");
}
else
{
// Output if the element is found
Console.WriteLine("Found element {0}.", foundElement.Name);
}
Console.WriteLine("[Press any key to finish]");
Console.ReadKey();
}
}
}
The code uses the method List.Find to get the result, it will only return the first match.
I would also suggest to migrate to String.Compare if you want to have case-insensitive comparison.
And finally I would be reading the data form file or a database, but that is beyond the question.

Best way to read rapidshare API response?

I've started working with the rapidshare.com API. I'm just wondering what is the best way to read the reply from and API call.
To be honest I think the API is all over the place. Some replies are comma delimited which is fine. I'm having with problems with the account info response. This is not comma delimited and the fields may not always be in the same order.
Here is a sample response:
accountid=123456 type=prem servertime=1260968445 addtime=1230841165 validuntil=1262377165 username=DOWNLOADER directstart=1 protectfiles=0 rsantihack=0 plustrafficmode=0 mirrors= jsconfig=1 email=take#hike.com lots=0 fpoints=12071 ppoints=10 curfiles=150 curspace=800426795 bodkb=5000000 premkbleft=23394289 ppointrate=93
I'm thinking that regex is the way to go here. Here is my expression that seems to cath all responses that contain values:
(accountid|type|servertime|addtime|validuntil|username|directstart|protectfiles|rsantihack|plustrafficmode|mirrors|jsconfig|email|lots|fpoints|ppoints|curfiles|curspace|bodkb|premkbleft|ppointrate|refstring|cookie)\=[\w._#]+
If the order of data is to be considered random then how do I determine which value is which?
I'm just curious as to how everybody else is working with this.
Thanks,
Conor
i assume c#.
string[] s = #"accountid=123456 type=prem servertime=1260968445 addtime=1230841165 validuntil=1262377165 username=DOWNLOADER directstart=1 protectfiles=0 rsantihack=0 plustrafficmode=0 mirrors= jsconfig=1 email=take#hike.com lots=0 fpoints=12071 ppoints=10 curfiles=150 curspace=800426795 bodkb=5000000 premkbleft=23394289 ppointrate=93".Split(" ");
var params = new Dictionary<string, string>();
foreach(var l in s)
{
var tmp = l.Split("=");
params[tmp[0]] = params[tmp[1]];
}
(it may contain bugs.. but the idea is obvious?)
You probably want to split this up into a Dictionary object of some kind, so that you can access the value by a key.
Here's an example of a C# console application that works with .NET 3.5:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace SO
{
class Program
{
static void Main(string[] args)
{
string input = #"accountid=123456 type=prem servertime=1260968445";
string pattern = #"(?<Key>[^ =]+)(?:\=)(?<Value>[^ ]+)(?=\ ?)";
Dictionary<string, string> fields =
(from Match m in Regex.Matches(input, pattern)
select new
{
key = m.Groups["Key"].Value,
value = m.Groups["Value"].Value
}
).ToDictionary(p => p.key, p => p.value);
//iterate over all fields
foreach (KeyValuePair<string, string> field in fields)
{
Console.WriteLine(
string.Format("{0} : {1}", field.Key, field.Value)
);
}
//get value from a key
Console.WriteLine(
string.Format("{0} : {1}", "type", fields["type"])
);
}
}
}
Link to another example in PHP:
How to use rapidshare API to get Account Details ?? PHP question
Here is what I have done.
It's basically just a working version the code from Yossarian.
// Command to send to API
String command = "sub=getaccountdetails_v1&type=prem&login="+Globals.username+"&password="+Globals.password;
// This will return the response from rapidshare API request.
// It just performs # webrequest and returs the raw text/html. It's only a few lines. Sorry I haven't included it here.
String input = executeRequest(command);
input = input.Trim();
string[] s = input.Split('\n');
Dictionary<string,string> terms = new Dictionary<string, string>();
foreach(var l in s)
{
String[] tmp = l.Split('=');
terms.Add(tmp[0], tmp[1]);
}
foreach (KeyValuePair<String, String> term in terms)
{
txtOutput.Text += term.Key + " :: " + term.Value+"\n";
}
Thanks for your help guys.

Categories

Resources