Read File by Splitting Each Row in 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
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(" ", "")

Related

Converting open file to save file dialog not working [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 4 months ago.
Improve this question
So Dai fixed my problem with the openfiledialog but then i started working on save file,
here is the code i made but it did not work/ i can't think of a way to get it to work.
const String FILTER_LUA = "Lua scripts (*.lua)|*.lua";
const String FILTER_TXT = "Text files (*.txt)|*.txt";
const String FILTER_ALL = "All files (*.*)|*";
// ...
SaveFileDialog sfd = new SaveFileDialog()
{
// InitialDirectory = AppDomain.CurrentDomain.BaseDirectory,
InitialDirectory = Environment.CurrentDirectory,
Filter = FILTER_LUA + "|" + FILTER_TXT + "|" + FILTER_ALL,
Title = "Open Script"
};
Boolean? result = sfd.ShowDialog();
if ((result ?? false) && File.Exists(sfd.FileName))
{
String fileText = File.ReadAllText(sfd.FileName);
this.TextEditor.Text = fileText;
}
SaveFileDialog is meant to pick a file path to save data to. In your case you would have to write the TextEditor.Text value to the picked file using the File.WriteAllText or the asynchronous File.WriteAllTextAsync method:
private const string FILTER_LUA = "Lua scripts (*.lua)|*.lua";
private const string FILTER_TXT = "Text files (*.txt)|*.txt";
private const string FILTER_ALL = "All files (*.*)|*";
private async Task SaveTextBoxToFileAsync()
{
var sfd = new SaveFileDialog()
{
// InitialDirectory = AppDomain.CurrentDomain.BaseDirectory,
InitialDirectory = Environment.CurrentDirectory,
Filter = $"{FILTER_LUA}|{FILTER_TXT}|{FILTER_ALL}",
Title = "Open Script"
};
bool? result = sfd.ShowDialog();
if (result ?? false)
{
await File.WriteAllTextAsync(sfd.FileName, this.TextEditor.Text);
}
}
Usage
await SaveTextBoxToFileAsync();

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()));

how to read a 2D array from a txt file ? 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
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");
}
}
}
}

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