How to convert string from text file to Int - c#

I'm trying to read from a text file which contains strings of numbers and I want to be able to convert each line from the file into Int and store it in an array so I am able to do maths on it later date.
This is what I have tried within Visual Studio and it gives a message of "System.FormatException: 'Input string was not in a correct format.'".
static void Main(string[] args)
{
using (StreamReader List1 = new StreamReader("path of text file.txt"))
{
string input;
List<string> High256 = new List<string>();
while((input = List1.ReadLine()) != null)
{
Convert.ToInt32(input);
}
High256.Add(input);
Console.WriteLine(High256);
}
}

You need to check if you can convert to an int or not first.
static void Main(string[] args)
{
var List1 = new File.ReadAllLines("path of text file.txt");
string input;
List<string> High256 = new List<string>();
foreach(var item in List1)
{
if(int.TryParse(item?.Trim(), out var tempInt))
{
High256.Add(tempInt);
Console.WriteLine(High256);
}
}
}
or in one line:
var list = File.ReadAllLines("path")
.Where(x => int.TryParse(x, out var temp))
.Select(t=>int.Parse(t.Trim())).ToList();

You can use Linq and do next thing:
int[] array = File.ReadAllLines("path").Select(t=>Convert.ToInt32(t)).ToArray();
this will read all lines from file and convert each line to int32 type,finally you get int array!

Related

Read lines of data from CSV then display data

I have to read info from a txt file, store it in a manner (array or list), then display the data. Program must include at least one additional class.
I've hit a wall and can't progress.
string, string, double, string
name,badge,salary,position
name,badge,salary,position
name,badge,salary,position
I'm sorry and I know the code below is disastrous but I'm at a loss and am running out of time.
namespace Employees
{
class Program
{
static void Main()
{
IndividualInfo collect = new IndividualInfo();
greeting();
collect.ReadInfo();
next();
for (int i = 0; i < 5; i++)
{
displayInfo(i);
}
exit();
void greeting()
{
Console.WriteLine("\nWelcome to the Software Development Company\n");
}
void next()
{
Console.WriteLine("\n*Press enter key to display information . . . *");
Console.Read();
}
void displayInfo(int i)
{
Console.WriteLine($"\nSoftware Developer {i + 1} Information:");
Console.WriteLine($"\nName:\t\t\t{collect.nameList[i]}");
}
void exit()
{
Console.WriteLine("\n\n*Press enter key to exit . . . *");
Console.Read();
Console.Read();
}
}
}
}
class IndividualInfo
{
public string Name { get; set; }
//public string Badge{ get; set; }
//public string Position{ get; set; }
//public string Salary{ get; set; }
public void ReadInfo()
{
int i = 0;
string inputLine;
string[] eachLine = new string[4];
string[,] info = new string[5, 4]; // 5 developers, 4x info each
StreamReader file = new StreamReader("data.txt");
while ((inputLine = file.ReadLine()) != null)
{
eachLine = inputLine.Split(',');
for (int x = 0; x < 5; x++)
{
eachLine[x] = info[i, x];
x++;
}
i++;
}
string name = info[i, 0];
string badge = info[i, 1];
string position = info[i, 2];
double salary = Double.Parse(info[i, 3]);
}
public List<string> nameList = new List<string>();
}
So far I think I can collect it with a two-dimensional array, but a List(s) would be better. Also, the code I've posted up there won't run because I can't yet figure out a way to get it to display. Which is why I'm here.
using System.IO;
static void Main(string[] args)
{
using(var reader = new StreamReader(#"C:\test.csv"))
{
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
listA.Add(values[0]);
listB.Add(values[1]);
}
}
}
https://www.rfc-editor.org/rfc/rfc4180
or
using Microsoft.VisualBasic.FileIO;
var path = #"C:\Person.csv"; // Habeeb, "Dubai Media City, Dubai"
using (TextFieldParser csvParser = new TextFieldParser(path))
{
csvParser.CommentTokens = new string[] { "#" };
csvParser.SetDelimiters(new string[] { "," });
csvParser.HasFieldsEnclosedInQuotes = true;
// Skip the row with the column names
csvParser.ReadLine();
while (!csvParser.EndOfData)
{
// Read current line fields, pointer moves to the next line.
string[] fields = csvParser.ReadFields();
string Name = fields[0];
string Address = fields[1];
}
}
http://codeskaters.blogspot.ae/2015/11/c-easiest-csv-parser-built-in-net.html
or
LINQ way:
var lines = File.ReadAllLines("test.txt").Select(a => a.Split(';'));
var csv = from line in lines
select (from piece in line
select piece);
^^Wrong - Edit by Nick
It appears the original answerer was attempting to populate csv with a 2 dimensional array - an array containing arrays. Each item in the first array contains an array representing that line number with each item in the nested array containing the data for that specific column.
var csv = from line in lines
select (line.Split(',')).ToArray();
This question was fully addressed here:
Reading CSV file and storing values into an array

FileStream Class C# Input from txt file to array

I am trying to make use of StreamReader and taking data from text files and store it into an array. I am having an issue where I think the fix is simple, but I am stumped. When I print the array, it prints every single token in the txt file instead of the single line of data containing the search name along with the 11 int tokens.
Long_Name.txtsample
public class SSA
{
public void Search()
{
Console.WriteLine("Name to search for?");
string n = Console.ReadLine();
Search(n, "Files/Names_Long.txt");
}
public int[] Search(string targetName, string fileName)
{
int[] nums = new int[11];
char[] delimiters = { ' ', '\n', '\t', '\r' };
using (TextReader sample2 = new StreamReader("Files/Exercise_Files/SSA_Names_Long.txt"))
{
string searchName = sample2.ReadLine();
if (searchName.Contains(targetName))
{
Console.WriteLine("Found {0}!", targetName);
Console.WriteLine("Year\tRank");
}
else
Console.WriteLine("{0} was not found!", targetName);
while (searchName != null)
{
string[] tokensFromLine = searchName.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
int arrayIndex = 0;
int year = 1900;
foreach (string token in tokensFromLine)
{
int arrval;
if (int.TryParse(token, out arrval))
{
nums[arrayIndex] = arrval;
year += 10;
Console.WriteLine("{0}\t{1}", year, arrval);
arrayIndex++;
}
}
searchName = sample2.ReadLine();
}
}
return nums;
}
}
That sure is a lot of code, this snippet does not account for duplicates but if you were willing to work with linq, something like this might help? You could also just iterate over the file_text array using a for-loop and perhaps set your return array in that. Anyway a lot less code to mess with
public int[] Search(string targetName, string fileName)
{
List<string> file_text = File.ReadAllLines("Files/Exercise_Files/SSA_Names_Long.txt").ToList();
List<string> matching_lines = file_text.Where(w => w == targetName).ToList();
List<int> nums = new List<int>();
foreach (string test_line in matching_lines)
{
nums.Add(file_text.IndexOf(test_line));
}
return nums.ToArray();
}

Text file to two string arrays in wpf using streamreader

I'm trying to read a text file to two string arrays. Array1 is to be all the odd lines, array2 all the even lines. I then add all the items of array1 to a combobox and when that is selected, or as it gets typed, outputs array2 to a textbox.
So far, I have tried a few methods from here, but the big issue seems to be creating the arrays. I tried to get help here before, but the answers didn't actually answer my question. They must be arrays, not lists (which I tried and worked well). I am really confused by this whole thing and my attempted code is now rubbish:
private void ReadFile(string filePath, string customerPhone, string customerName)
{
string line = string.Empty;
var fileSR = new StreamReader(filePath);
bool number = true;
while((line = fileSR.ReadLine()) != null)
{
if (number)
{
customerPhone(line);
number = false;
}
else
{
customerName(line);
number = true;
}
}
fileSR.Close();
}
I'm losing confidence in this whole process, but I need to find a way to make it work, then I can learn why it does.
You are almost there, just use the List<string>.
private void ReadFile(string filePath, string customerPhone, string customerName)
{
string line = string.Empty;
using (var fileSR = new StreamReader(filePath))
{
bool number = true;
List<string> customerPhone = new List<string>();
List<string> customerName = new List<string>();
while((line = fileSR.ReadLine()) != null)
{
if (number)
{
customerPhone.Add(line);
number = false;
}
else
{
customerName.Add(line);
number = true;
}
}
fileSR.Close();
}
}
If you are interested only in Arrays, you could simply call customerName.ToArray() to convert it to an array.
Linq Solution
Alternatively you could use Linq and do this.
var bothArrays = File.ReadLines("filepath") // Read All lines
.Select((line,index) => new {line, index+1}) // index each line
.GroupBy(x=> x/2) // Convert into two groups
.SelectMany(x=> x.Select(s=>s.line).ToArray()) // Convert it to array
.ToArray();
You should use collections to return data, say IList<String>:
private static void ReadFile(String filePath,
IList<String> oddLines,
IList<String> evenLines) {
oddLines.Clear();
evenLines.Clear();
int index = 1; //TODO: start with 0 or with 1
foreach (String line in File.ReadLines(filePath)) {
if (index % 2 == 0)
evenLines.Add(line);
else
oddLines.Add(line);
index += 1;
}
}
using
List<String> names = new List<String>();
List<String> phones = new List<String>();
ReadFile(#"C:\MyDate.txt", names, phones);
// If you want array representation
String[] myNames = names.ToArray();
String[] myPhones = phones.ToArray();
// Let's print out names
Console.Write(String.Join(Envrironment.NewLine, names));
Please, notice, that using File.ReadLines usually more convenient than StreamReader which should be wrapped in using:
// foreach (String line in File.ReadLines(filePath)) equals to
using (var fileSR = new StreamReader(filePath)) {
while ((line = fileSR.ReadLine()) != null) {
...
}
}
This worked! I have these class level strings:
string cFileName = "customer.txt";
string[] cName = new string[0];
string[] cPhone = new string[0];
And then this in the Window Loaded event, but could be used in it's own method:
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
//read file on start
int counter = 0;
string line;
StreamReader custSR = new StreamReader(cFileName);
line = custSR.ReadLine();
while (custSR.Peek() != -1)
{
Array.Resize(ref cPhone, cPhone.Length + 1);
cPhone[cPhone.Length - 1] = line;
counter++;
line = custSR.ReadLine();
Array.Resize(ref cName, cName.Length + 1);
cName[cName.Length - 1] = line;
counter++;
line = custSR.ReadLine();
phoneComboBox.Items.Add(cPhone[cPhone.Length - 1]);
}
custSR.Close();
//focus when program starts
phoneComboBox.Focus();
}

Splitting string on unique partrs, sort and concatenate again

I'm just learning C#, so please don't blame me if the solution is obvious.
I have comma-delimeted string. I want to split it, remove duplicates from splitted array, sort result array and then concatenate again.
E.g. for string "3,a,b,3,a,c,s,3,1,2,3,3" result should be: "1,2,3,a,b,c,s"
What I've tried so far is next code:
static void Main(string[] args)
{
string myStr = "3,a,b,3,a,c,s,3,1,2,3,3";
string[] temp = myStr.Split(',');
string res = "";
List<string> myList = new List<string>();
foreach (var t in temp)
{
if (myList.Contains(t)==false){
myList.Add(t);
}
}
myList.Sort();
foreach(var t in myList){
res+=t +",";
}
res = res.Substring(0, res.Length - 1);
Console.WriteLine(res);
}
But I believe there is more effificent way..
Thanks in advise.
Try this single line:
Console.WriteLine(string.Join(",",myStr.Split(',').Distinct().OrderBy(x=>x)));

C# List to Array Problem

Still new to C# so be gentle :)
I have some code which reads in a CSV file and stores the output in a List. I used a List instead of an Array as the number of entries in the CSV is undetermined. Once the List is created from the file I then want to pass it to a Shell sort method as this is the purpose of the program. To do this I first want to convert the list to an array of integers. I have tried the .ToArray method but it doesnt seem to be working for me. I get an exception
Cannot Implicilty convert type String[][] to string[].
I know I am doing something stupid but cant seem to find out what... Any help would be appreciated.
//Import DAT file and format it.
public int[] ImportDat(string path)
{
List<string[]> loadedData = new List<string[]>();
loadedData.Clear();
try
{
using (StreamReader readCSV = new StreamReader(path))
{
string line;
string[] row;
while ((line = readCSV.ReadLine()) != null)
{
row = line.Split(',');
loadedData.Add(row);
}
}
}
catch
{
MessageBox.Show("Import Failed. Please check the file is in the same folder as the executable");
}
string[] MyArray = loadedData.ToArray();
//temp Array to return a value
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
return numbers;
}
It seems like you really want a one dimensional list of numbers from your CSV file, but you are treating each row separately right now. If that is the case then use:
loadedData.AddRange(row);
instead of:
loadedData.Add(row);
and declare loadedData as List<string>. Now you still would have to do the conversion to int, since your method returns a list of int.Using LINQ you could do:
List<int> results = loadedData.Select(s=> Convert.ToInt32(s)).ToList();
Your method also could be fully expressed with LINQ like this:
public int[] ImportDat(string path)
{
List<int> result = File.ReadAllLines(path)
.Select(line => line.Split(','))
.SelectMany(s => s)
.Select( s=> Convert.ToInt32(s))
.ToList();
return result;
}
Your variable loadedData is a List of string arrays. Calling .ToArray() on it will return a string[][] (2 dimensional array), not a string[].
Why don't you just use the list and convert the numbers right away?
public int[] ImportDat(string path)
{
List<int> loadedData = new List<int>();
loadedData.Clear();
try
{
using (StreamReader readCSV = new StreamReader(path))
{
string line;
string[] row;
while ((line = readCSV.ReadLine()) != null)
{
row = line.Split(',');
foreach(var token in row)
{
loadedData.Add(Convert.ToInt32(token));
}
}
}
}
catch
{
MessageBox.Show("Import Failed. Please check the file is in the same folder as the executable");
}
return loadedData.ToArray();
}
You are declaring loadedData as a list of string arrays. You should just do
List<string> loadedData = new List<string>();
The problem is that each item in your List, is an array of strings.
it's not a list of string.
hench, you should make your "MyArray" a two dimensional array of strings.
in other words, an array of arrays of strings.
so in short: string[][] MyArray = loadedData.ToArray();
Perhaps you can modify this code to suit your needs?
List<int> numbersList = new List<int>();
string input = "2,4,6,3";
string[] numbersStringArray = input.Split(',');
foreach (var numberString in numbersStringArray)
{
numbersList.Add(Convert.ToInt32(numberString));
}
int[] numbersArray = numbersList.ToArray<int>();

Categories