How to read numbers in a .txt file to an integer array? - c#

I have a file that I need to save as an array. I am trying to convert a text file to an integer array using StreamReader. I just am unsure as to what to put in the for loop at the end of the code.
This is what I have so far:
//Global Variables
int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//code to load the numbers from a file
OpenFileDialog fd = new OpenFileDialog();
//open the file dialog and check if a file was selected
if (fd.ShowDialog() == DialogResult.OK)
{
//open file to read
StreamReader sr = new StreamReader(fd.OpenFile());
int Records = int.Parse(sr.ReadLine());
//Assign Array Sizes
Original = new int[Records];
int[] OriginalArray;
for (int i = 0; i < Records; i++)
{
//add code here
}
}
The .txt file is:
5
6
7
9
10
2
PS I am a beginner, so my coding skills are very basic!
UPDATE: I have previous experience using Line.Split and then mapping file to arrays but obviously that does not apply here, so what do I do now?
//as continued for above code
for (int i = 0; i < Records; i++)
{
int Line = int.Parse(sr.ReadLine());
OriginalArray = int.Parse(Line.Split(';')); //get error here
Original[i] = OriginalArray[0];
}

You should just be able to use similar code to what you had above it:
OriginalArray[i] = Convert.ToInt32(sr.ReadLine());
Every time the sr.ReadLine is called it increments the data pointer by 1 line, hence iterating through the array in the text file.

try this
OpenFileDialog fd = new OpenFileDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
StreamReader reader = new StreamReader(fd.OpenFile());
var list = new List<int>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
int value = 0;
if (!string.IsNullOrWhiteSpace(line) && int.TryParse(line, out value))
list.Add(value);
}
MessageBox.Show(list.Aggregate("", (x, y) => (string.IsNullOrWhiteSpace(x) ? "" : x + ", ") + y.ToString()));
}

You can read the entire file into a string array, then parse (checking the integrity of each one).
Something like:
int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//code to load the numbers from a file
var fd = new OpenFileDialog();
//open the file dialog and check if a file was selected
if (fd.ShowDialog() == DialogResult.OK)
{
var file = fd.FileName;
try
{
var ints = new List<int>();
var data = File.ReadAllLines(file);
foreach (var datum in data)
{
int value;
if (Int32.TryParse(datum, out value))
{
ints.Add(value);
}
}
Original = ints.ToArray();
}
catch (IOException)
{
// blah, error
}
}
}

Another way to do it if you'd like to read to the end of the file and you don't know how long it is with a while loop:
String line = String.Empty;
int i=0;
while((line = sr.ReadLine()) != null)
{
yourArray[i] = Convert.ToInt32(line);
i++;
//but if you only want to write to the file w/o any other operation
//you could just write w/o conversion or storing into an array
sw.WriteLine(line);
//or sw.Write(line + " "); if you'd like to have it in one row
}

//using linq & anonymous methods (via lambda)
string[] records = File.ReadAllLines(file);
int[] unsorted = Array.ConvertAll<string, int>(records, new Converter<string, int>(i => int.Parse(i)));

Related

How to link users file selection to a StringSplit

I'm trying to get the users chosen file to split into an array which is separated by , and /t.
The user can choose a file at the top of the code but how do I get their choice to split into an array lower down when they press the ValidateButton
The text file or ordered in this way
info,info,info,
info,info,info,
info,info,info,
If I can get them into an array then I can easily organises the data.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\"; // Start in C: drive
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.RestoreDirectory = true;
openFileDialog1.DefaultExt = "txt"; // Extension of file is txt
openFileDialog1.Filter = "Text|*.txt||*.*"; //Only text files
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileNameBox.Text = openFileDialog1.FileName; // Chosen file name is displayed in text box
var fileStream = openFileDialog1.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
var fileContent = reader.ReadToEnd();
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//This is the file path the user has chosen
}
public void ValidateButton_Click(object sender, EventArgs e)
{
//Call Multi line text box
//Call PROGRESS BAR_
int counter = 0;
string lines;
string Patient = lines;
string[] split = Patient.Split(new Char[] { ',', '\t' });
foreach (string s in split)
if (s.Trim() != "")
Console.WriteLine(s);
{
Console.WriteLine(lines);
counter++;
}
Console.WriteLine("There were {0} records.", counter);
Console.ReadKey();
}
List<string> temp = new List<string>();
string[] finalArray;
using (StreamReader reader = new StreamReader(fileStream))
{
// We read the file then we split it.
string lines = reader.ReadToEnd();
string[] splittedArray = lines.Split(',');
// We will check here if any of the strings is empty (or just whitespace).
foreach (string currentString in splittedArray)
{
if (currentString.Trim() != "")
{
// If the string is not empty then we add to our temporary list.
temp.Add(currentString);
}
}
// We have our splitted strings in temp List.
// If you need an array instead of List, you can use ToArray().
finalArray = temp.ToArray();
}

Save Opened Text File to Original Location

I am creating an application that will allow me to open a .txt file and edit the values (weight=60, height =50, etc) in a DataGridView. My issue is that I am able to upload the .txt file using OpenFileDialog but am unable to write over and save it in it's previous location.
For clarification, here is my method to upload text files:
private void btnUpload_Click(object sender, EventArgs e)
{
Stream myStream;
openFileDialog1.FileName = string.Empty;
openFileDialog1.InitialDirectory = "C:\\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var compareType = StringComparison.InvariantCultureIgnoreCase;
var fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
var extension = Path.GetExtension(openFileDialog1.FileName);
if (extension.Equals(".txt", compareType))
{
try
{
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(openFileDialog1.FileName);
StreamReader reader = new StreamReader(openFileDialog1.FileName);
string line;
while ((line = reader.ReadLine()) != null)
{
string[] words = line.Split('=');
paramList.Add(new Parameter(words[0], words[1]));
}
BindGrid();
}
}
And what I've tried to save the file:
public void WriteToTextFile(DataGridView dgvParam)
{
String file_name = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
using (StreamWriter objWriter = new StreamWriter(openFileDialog1.FileName))
{
for (Int32 row = 0; row < dgvParam.Rows.Count - 1; row++)
{
StringBuilder sb = new StringBuilder();
for (Int32 col = 0; col < dgvParam.Rows[row].Cells.Count; col++)
{
if (!String.IsNullOrEmpty(sb.ToString()))
sb.Append("="); //any delimiter you choose
sb.Append(dgvParam.Rows[row].Cells[col].Value.ToString().ToUpper());
}
objWriter.WriteLine(sb.ToString());
}
}
It says it is openFileDialog is currently in use and it cannot reach it! Any suggestions or recommendations would be really appreciated!
You need to dispose your reader variable.
You should get rid of the first using statement entirely and wrap that in a using statement instead.

Importing file to array

I want the user to be able to chose a text file written in a certain way (1 number per line) and then have the file converted into an array. I have bits and pieces of it working but I cant get it to all work at the same time. Any help would be appreciated.
private void Load_Button_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
List<int> list = new List<int>();
string fileName = "";
//OpenFileDialog ofd = new OpenFileDialog();
//ofd.Filter = "TXT File|*.txt";
//ofd.Title = "Open File";
// if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
// {
File_Label.Text = "C:/Users/Neilan/Desktop/sample.txt";
//fileName = "#" + ofd.SafeFileName;
//MessageBox.Show(ofd.FileName);
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Users\Neilan\Desktop\sample.txt");
while ((line = file.ReadLine()) != null)
{
Unsorted_Box.Text += line + ", ";
//list.Add(int.Parse(fileName));
counter++;
}
dataArray = list.ToArray();
// }
}
You can do this.
var numberarray = File.ReadAllLines("stringpath").Select(int.Parse).ToArray();
Looking at your code, I guess you want to show these values in comma separated format to user. You can achieve this with following code snippet.
Unsorted_Box.Text = String.Join(",", numberarray.ToArray());
Hope this helps !
This problem can be solved by one line
var resultArray = Array.ConvertAll(System.IO.File.ReadAllLines("filename.type"), str => int.Parse(str));
Instead of "filename.type" you can put something like File_Label.Text

csv file reading only first line

I'm trying to upload a series of client info's through a csv ,I had some trouble with this in the eginning but my previous post was answered so I was able to start reading in the data however it only reads the first line. Just wondering if anyone had any ideas. I've included the code below
private void btnUpload_Click(object sender, EventArgs e)
{
//Browse for file
OpenFileDialog ofd = new OpenFileDialog();
//Only show .csv files
ofd.Filter = "Microsoft Office Excel Comma Separated Values File|*.csv";
DialogResult result = ofd.ShowDialog();
//If the user selects a valid file
if (result == DialogResult.OK)
{
//File is delimited by a comma
char[] laClientDelim = { ',' };
//New object for string manipulation
objStringManipulation = new StringManipulation();
// Parse the csv file
List<string[]> lsClientList = objStringManipulation.parseCSV(ofd.FileName, laClientDelim);
foreach (string[] laClient in lsClientList)
{
//Create new object for manipulating the database
objSqlCommands = new SqlCommands("Client", "ClientName");
string[] records = File.ReadAllLines(ofd.FileName); // read the file completely line by line
char splitChar = ',';
int splitCharCount = 0;
int k = 0;
string[] fields = records[k].Split(splitChar); // reads all the single values per line. 'splitChar' should be the delimiter.
splitCharCount++;
if (splitCharCount >= 4 && splitCharCount <= 10)
{
var stuff = from l in File.ReadLines(ofd.FileName)
let x = l.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Skip(1)
.Select(s => char.Parse(s))
select new
{
Client = x,
ClientName = x
};
}
//Inserts the client info into datbase
objSqlCommands.sqlCommandInsertorUpdate("INSERT", records[k]);//laClient[0]);
k++;
//Refreshs the Client table on display from the
this.clientTableAdapter.Fill(this.kIIDImplementationCalcDataSet.Client);
//MAKE SURE TO ONLY ADD IN CLIENT AND CLIENT NAME
//update the view
dgvClientlst.Update() ;
}
}
}
your loop looks like this essentially :
foreach (string[] laClient in lsClientList)
{
int k = 0;
string[] records = File.ReadAllLines(ofd.FileName);
string[] fields = records[k].Split(splitChar);
k++;
}
Your 'k' value never makes it past 0 for each laClient. You need to loop internally for each line.
I know my answer is not exactly what you are looking for but if you convert the .csv file to .xls file then you can manipulate it very easily. I have done this on multiple occasions and if you want I can provide you instructions with code.
Expanding on Jonesy's answer (because I can't yet comment), declare the variable k outside the loop. It's being reset to zero each time through.
int k = 0;
foreach (string[] laClient in lsClientList)
{
string[] records = File.ReadAllLines(ofd.FileName);
string[] fields = records[k].Split(splitChar);
k++;
}

File name from StreamReader C# - asp.net MVC3 to array

my application is MVC3 C#; I am populating two dropdownlists using json using the following:
public ActionResult CheckWord(string cword)
{
try
{
List<string[]> arrayList = new List<string[]>();
List<string[]> stateList = new List<string[]>();
//
List<string[]> fileList = new List<string[]>();
//
string[] filePaths = Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath("/Video"), "*.srt");
string[] fnList = new string[filePaths.Length];
for (int i = 0; i < fnList.Length; ++i)
{
FileInfo fi = new FileInfo(filePaths[i]);
fnList[i] = fi.Name.Substring(0, fi.Name.LastIndexOf(".srt"));
}
int nFiles = filePaths.Length;
string cacheline = "";
string line;
for (int i = 0; i < nFiles; ++i)
{
StreamReader file = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("/Video/" + fnList[i] + ".srt"));
List<string> lines = new List<string>();
List<string> statments = new List<string>();
//
List<string> fnames = new List<string>();
//
while ((line = file.ReadLine()) != null)
{
if (line.Contains(cword))
{
statments.Add(line);
// fnames.Add(file);
lines.Add(cacheline);
}
cacheline = line;
}
file.Close();
var array = lines.ToArray();
arrayList.Add(array);
stateList.Add(statments.ToArray());
}
return Json(new { success = true, fnList = fnList, arrayList = arrayList.ToArray(), stateList = stateList.ToArray() });
}
catch { }
return Json(new { success = false });
}
I am checking if a word exists in a group of files; then display the names of files in one dropdownlist and the lines from each file in the other dropdownlist. It works fine, however it gives me a list of all files becasue I am sending back fnlist. However I am trying to display only the files that contain that word; I could not get the file name from the StreamReader and add it to an array fileList. I would appreciate your suggestions, thanks in advance.
Already so many lists! Why not another? You already open the file with fnList[i] within the context of the loop, so...
List<string[]> results = new List<string[]>();
....
while ((line = file.ReadLine()) != null) {
if (line.Contains(cword)) {
results.Add(fnList[i]);
break; // optional, if possible, but if you need to continue check for dupes
}
}
....
return Json(new {
success = true,
fnList = results.ToArray(),
arrayList = arrayList.ToArray(),
stateList = stateList.ToArray()
});
System.IO.StreamReader file = new System.IO.StreamReader("setup.txt");
Later on, we would like to print the name of the file being used by stream reader.
eg, if there is an error, I would like a message box that displays "error reading file: 'filename'"
MessageBox.Show("Error loading " + ((FileStream)file.BaseStream).Name);
Not sure what exactly you are looking for but since you are creating StreamReader from a file name why not have file name in a separate variable and use it later:
var fileName = System.Web.HttpContext.Current.Server.MapPath(
"/Video/" + fnList[i] + ".srt");
StreamReader file = new StreamReader(fileName);

Categories

Resources