how to read a 2D array from a txt file ? C# [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So that is my crappy code
class begin
{
public static string[] Reader()
{
string[] theMap = System.IO.File.ReadAllLines(#"C:\Users\Public\Console Slayer\Map\map.txt");
string[] Map = theMap.Clone() as string[];
return Map;
}
public static void Printer()
{
foreach (string line in Reader())
{
Console.WriteLine(line);
}
}
static void Main()
{
Reader();
Printer();
}
}
I want to make the Map string into an 2D array for a feature use.
I am new to programing and i know my code is bad.

Try using
Microsoft.VisualBasic.FileIO.TextFieldParser
Yes, it is a VB component, but it works. No need to reinvent the wheel. Sample usage:
OpenFileDialog od = new OpenFileDialog();
od.Filter = "Tab delimited file (*.txt)|*.txt";
if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (var reader = new Microsoft.VisualBasic.FileIO.TextFieldParser(od.FileName))
{
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
reader.Delimiters = new string[] { "\t" }; // the delimeter of the lines in your file
reader.ReadLine(); // skip header if needed, ignore titles
while (!reader.EndOfData)
{
try
{
var currentRow = reader.ReadFields(); // string array
// Include code here to handle the row.
}
catch (Microsoft.VisualBasic.FileIO.MalformedLineException vex)
{
MessageBox.Show("Line " + vex.Message + " is invalid. Skipping");
}
}
}
}

Related

Writing to txt file reach out of memory ? C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to write huge lines to a .txt file in a C# Application, around 20-30 thousand lines :
class Program
{
static void Main(string[] args)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
List <string> firstListTrade= new List<string>();
List <string> secondListTrade= new List<string>();
firstListTrade= System.IO.File.ReadAllLines(#"C:\Users\me\Desktop\File1.txt").ToList();
secondListTrade=System.IO.File.ReadAllLines(#"C:\Users\me\Desktop\Fil2.txt").ToList();
string resultOne = "C:\\Users\\me\\Desktop\\resultOutput1.txt";
string resultatsTwoo = "C:\\Users\\elbb001\\Desktop\\resultOutput2.txt";
//Sorting lists
firstListTrade= firstListTrade.OrderBy(q => q).ToList();
secondListTrade= secondListTrade.OrderBy(q => q).ToList();
// Write the string array to a new file named "WriteLines.txt".
StreamWriter outputFileOne = new StreamWriter(resultatsOne);
StreamWriter outputFileTwoo = new StreamWriter(resultatsTwoo);
int i = firstListTrade.Count();
int j = secondListTrade.Count();
int endofFile = 0;
foreach (string trade in secondListTrade)
{
endofFile++;
if (!firstListTrade.Contains(trade))
{
outputFileOne.WriteLine("Number : " + trade + " exist in first list but not second");
}
if(endofFile==i)
{
outputFileOne.WriteLine("End of file : " + endofFile);
}
outputFileOne.Flush();
}
endofFile = 0;
foreach (string trade in firstListTrade)
{
endofFile++;
if (!secondListTrade.Contains(trade))
{
outputFileTwoo.WriteLine("Number : " + trade + " exist in second but not in first ");
}
if (endofFile == j)
{
outputFileTwoo.WriteLine("End of file : "+ endofFile);
}
}
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
// Keep the console window open in debug mode.
Console.WriteLine("Done in : " + elapsedMs.ToString());
System.Console.ReadKey();
}
}
And I compiled and received no error , but when I opened the file I saw the results I want , but when I scrolled all the way down I noticed at the end of file this sentence :
" Trade number : 22311 "
But when I used breakpoints on the end of file , it was reached in code but not written in the file?
What could have gone wrong? Did it reach out of memory? or the txt file can't write anymore?
According to new question, here is the answer:
StreamWriter outputFileTwoo = new StreamWriter(resultatsTwoo);
List <string> firstListThatIcantRevealItName= new List<string>();
List <string> secondListThatIcantRevealItName= new List<string>();
firstListThatIcantRevealItName=System.IO.File.ReadAllLines(#"C:\Users\me\Desktop\blabla.txt").ToList();
secondListThatIcantRevealItName=System.IO.File.ReadAllLines(#"C:\Users\me\Desktop\potto.txt").ToList();
using(StreamWriter outputFileOne = new StreamWriter(resultatsOne))
{
foreach (string trade in secondListThatIcantRevealItName)
{
endofFile++;
if (!secondListThatIcantRevealItName.Contains(trade))
{
outputFileOne.WriteLine("Trade number : " + trade + " exist in first list but not in second list ");
}
if(endofFile==i)
{
outputFileOne.WriteLine(endofFile);
}
}
}

Separating uppercase and lowercase on a string C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
can someone please suggest a method wherein i can separate uppercase characters and lowercase characters in a string
input : "heLLoWorLd"
output : "heoordLLWL"
I have prepare one program for you to doing the same:
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main()
{
// Input string.
string mixedCase = "heLLoWorLd";
// Call ToLower instance method, which returns a new copy.
string lower = "";
string uper = "";
for (int i = 0; i < mixedCase.Length; i++)
{
if (char.IsLower(mixedCase[i]))
lower = lower + mixedCase[i];
else
uper = uper + mixedCase[i];
}
// Display results.
Console.WriteLine("{0}{1}",
lower,
uper);
}
}
OUTPUT:
heoordLLWL
This code will definitely helpful to you.Thank you!
You can make use of few extension methods like the following:
string strInput="heLLoWorLd";
string outputStr =String.Join("",strInput.GroupBy(x=>Char.IsLower(x))
.SelectMany(y=>y.ToList()));
You can try a working example here
Why not just a simple OrderBy? Imo GroupBy and SelectMany is a bit cracking a nut with a sledgehammer
string input = "heLLoWorLd";
string output = string.Concat(input.OrderBy(char.IsUpper)); // heoordLLWL
Try this:
 string input = "heLLoWorLd";
string output = string.Empty;
output = String.Concat(input.Where(c => Char.IsLower(c))) + String.Concat(input.Where(c => Char.IsUpper(c))) ;
Another way,
string str = "WeLcoMe";
string _upper = string.Empty, _lower = string.Empty;
foreach (var s in str)
{
if (char.IsUpper(s))
_upper += s;
else
_lower += s;
}
str = _upper + _lower;
Output will be
WLMecoe
string input = "heLLoWorLd";
StringBuilder builder = new StringBuilder();
StringBuilder upp = new StringBuilder();
StringBuilder low = new StringBuilder();
foreach (char c in input)
{
if (Char.IsLower(c))
{
low.Append(c);
}
else
{
if (Char.IsUpper(c))
{
upp.Append(c);
}
}
}
string output = low.ToString() + upp.ToString();
var input = "heLLoWorLd";
var output = string.Concat(input.GroupBy(char.IsLower).SelectMany(c => c.ToList()));

Read File by Splitting Each Row in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to read the File by Splitting each Row by removing whitespace through regex.split in c# but my code isn't working properly need help. Thanks in Advance.
text="";
OpenFileDialog open = new OpenFileDialog();
if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Stream filestream = open.OpenFile();
if (filestream != null)
{
string filename = open.FileName;
text = File.ReadAllText(filename);
}
string code = textBox1.Text;
columncounter = code.Length;
string[] arrays = Regex.Split(code, #"\s+");
textBox1.Text = text;
}
If you are trying to write each row, without whitespace, to your TextBox, this should work:
var result = new StringBuilder();
foreach (var line in File.ReadAllLines(filename))
{
result.AppendLine(Regex.Replace(line, #"\s", "")));
}
textBox1.Text = result.ToString();
For faster performance, use string.Replace:
var result = new StringBuilder();
foreach (var line in File.ReadAllLines(filename))
{
result.AppendLine(line
.Replace("\t", "")
.Replace("\n", "")
.Replace("\r", "")
.Replace(" ", ""));
}
textBox1.Text = result.ToString();
Just add textBox1.text = string.Concat(arrays). It will concatenate the strings from the splitted array.
or you could do something like text.Replace(" ", "")

Search a text file for 2 strings and then write all the lines between the strings to another file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hi I have a report file that has a lot of data and I need to split it up but report name.
So each report is labeled “Report1” then there is some data and then “Report1End” then the next report label “Report2” for example starts this repeats till the end of the file.
I would like to be able to have method that I could pass the file location, Report1, and Report1End to and then have it create a new file with Report1’s data.
Example of the file now
random junk
Report1
some stuff
some stuff
some stuff
some stuff
Report1End
random junk
Report2
some stuff
some stuff
some stuff
some stuff
Report2End
random junk random junk
Example of what I would like the output file to be
Report2
some stuff
some stuff
some stuff
some stuff
Report2End
Thanks for the help I used the example below and changed it a bit seems to work 100% for what I needed.
static IList<string> LinesBetween(string path, string start, string end)
{
var lines = new List<string>();
var foundStart = false;
foreach (var line in File.ReadLines(path))
{
Match SMatch = Regex.Match(line, start, RegexOptions.IgnoreCase);
if (!foundStart && SMatch.Success)
{ foundStart = true; }
if (foundStart)
{
Match EMatch = Regex.Match(line, end, RegexOptions.IgnoreCase);
if (EMatch.Success)
{ lines.Add(line); break; }
else { lines.Add(line); }
}
}
return lines;
}
static List<string> LinesBetween(string path, string start, string end)
{
var lines = new List<string>();
var foundStart = false;
foreach (var line in File.ReadLines(path))
{
if (!foundStart && line == start)
foundStart = true;
if(foundStart)
if (line == end) break;
else lines.Add(line);
}
return lines;
}
Sounds like a simple StreamReader/StreamWriter combination:
using (var reader = new StreamReader(inputFile))
{
using (var writer = new StreamWriter(outputFile))
{
string textLine;
while ((textline = reader.ReadLine()) != null)
{
// Check for your particular needs, and write
// to the output file if applicable
}
}
}
Invoke function like--> Fn("abc.txt", "Report2", "Report2End");
static string[] Fn(string path, string Start, string End) {
string[] vc = File.ReadAllLines(path);
int nStart= Array.IndexOf(vc,Start);
int nEnd =Array.IndexOf(vc,End);
return vc.Skip(nStart).Take((nEnd+1) - nStart).ToArray<string>();
}

read file and grab integer [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have txt file which contains number that I want to grab. This number has prefix which can be used to identify location inside file.
GeneratedNumber="120"
Number can be of any Int32 length value.
p.s. format of the file is .txt, one line contains more this key value pairs for example:
<Output Change="12.13" GeneratedNumber="120" Total="99.21" />
You can use the following code. Not very elegant or the best but tested and works fine.
string[] lines = File.ReadAllLines(Path.Combine(Application.StartupPath, "test.txt"));
foreach (string s in lines)
{
if (s.ToLowerInvariant().Contains("generatednumber"))
{
string temp = s.Substring(s.ToLowerInvariant().IndexOf("generatednumber"));
temp = temp.Substring(temp.IndexOf("\"") + 1);
temp = temp.Substring(0,temp.IndexOf("\""));
int yournumber;
if (int.TryParse(temp, out yournumber))
{
Console.WriteLine("Generated Number = ", yournumber);
}
}
}
I've only tested this as far as the xml side but this should work (You may wish to add error handling and the conversion to integers)
var values = new List<string>();
using(var sr = new StreamReader(fileName))
{
string line;
XmlDocument x = new XmlDocument();
while((line = sr.ReadLine()) != null)
{
x.LoadXml(line);
foreach(var node in x.GetElementsByTagName("Output"))
values.Add(node.Attributes["GeneratedNumber"].Value);
}
}
Tested using:
XmlDocument x = new XmlDocument();
x.LoadXml("<Output Change=\"12.13\" GeneratedNumber=\"120\" Total=\"99.21\" />");
Console.WriteLine(x.GetElementsByTagName("Output")[0]
.Attributes["GeneratedNumber"].Value);
Console.ReadLine();
you can use this code
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(#"C:\yourFile.txt");
foreach (string line in lines)
{
string sub = line.Substring(line.IndexOf("GeneratedNumber=") + 1);
int num = int.Parse(sub.IndexOf("\""));
// whatever you want to do with the integer
}
to read the text file lines and parse the lines after the "=" sign to integers.
depend on the look of the file you might use XmlDocument. please read about Xml here
string filePath = "your_file_path";
var match = System.Text.RegularExpressions.Regex.Match(
System.IO.File.ReadAllText(filePath),
#"GeneratedNumber=""(\d+)""",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
int num = match.Success ? int.Parse(match.Groups[1].Value) : 0;
Assuming there's only one instance of that number in the file or you want to grab only the first one even if there are multiple.
string[] lines = File.ReadAllLines("path to file");
Hashtable values = new Hashtable();
foreach (string line in lines)
{
if (line.Contains("=\""))
{
string[] split = line.Split('=');
values.Add(split[0], split[1].Replace("\"",""));
}
}
// GeneratedNumber is the value of GeneratedNumber in the file.
int GeneratedNumber = Int32.Parse(values["GeneratedNumber"].ToString());
This code should match your needs:
private static int GetNumber(string fileName)
{
string line;
string key = "GeneratedNumber=\"";
using (StreamReader file = new StreamReader(fileName))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(key))
{
int startIndex = line.IndexOf(key) + key.Length;
int endIndex = line.IndexOf("\"", startIndex);
return int.Parse(line.Substring(startIndex, endIndex - startIndex));
}
}
}
return 0;
}
Also you may be interested in these articles:
Using of StreamReader
String methods
Int32.Parse method

Categories