How to pad the required content to a text file - c#

Hi all i am doing an application where i write my data to the text file. What ever data that user enters on the form and click on save i will save that data to the text file that was chosen by the user . Assume my content is as follows
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234
I would like to pad the next 8 lines with the following
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
Lie that if i have 5 lines of text in the file i would like to pad the next 5 lines with the same as mentioned can any one tell how to do this
Each and every line length is '94'
Any number of lines can be there

var text = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234" + Environment.NewLine + "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234";
const String padWith = "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999";
const int lineNum = 10;
var lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
while(lines.Count < lineNum) {
lines.Add(padWith);
}
File.WriteAllLines(path, lines);

Here goes the code.
1) Find out the no of lines in your file
2) make count%10, if count%10==0 do not pad else 10-result=required
length , Pad with required length.
Sample code assume you have 8 lines
int cnt = 8;
int result = cnt % 10; // Will get 8
int iresult1 = 10 - result;
Hope it helps

Related

getting position of input string then get substring on both ends

I have a search function that searches keywords in a block of text and displays a truncated version of the results. My problem is that it will not show the searched keyword if its near the end.
For example.
Text = "A block of text is text that is grouped together in some way, such as with the use of paragraphs or blockquotes on a Web page. Often times, the text takes on the shape of a square or rectangular block"
I search for "times" with
text = text.Substring(0, 100) + "...";
It will return
"A block of text is text that is grouped together in some way, such as with the use of paragraphs or..."
Is there a way to return 100 characters before and after the searched keyword?
You can do this,
string s = "A block of text is text that is grouped together in some way, such as with the use of paragraphs or";
string toBeSearched = "grouped";
int firstfound = s.IndexOf(toBeSearched);
if (firstfound != -1 )
{
string before = s.Substring(0 , firstfound);
string after = s.Substring(firstfound + toBeSearched.Length);
}
DEMO
string s = "A block of text is text that is grouped together in some way, such as with the use of paragraphs or";
string wordtoSearch = "block";
int firstfound = s.IndexOf(wordtoSearch);
// If the index of the first letter found is greater than 100, get the 100 letters before the found word and 100 letters after the found word
if (firstfound > 100)
{
string before = s.Substring(firstfound , firstfound-100);
string after = s.Substring(firstfound + wordtoSearch.Length, 100);
Console.WriteLine(before);
Console.WriteLine(after);
}
//// If the index of the first letter found is less than 100, get the letters before the found word and 100 letters after the found word
if(firstfound < 100)
{
string before = s.Substring(0, firstfound);
Console.WriteLine(before);
if(s.Length >100)
{
string after = s.Substring(firstfound + wordtoSearch.Length, 100);
Console.WriteLine(after);
}
else
{
string after = s.Substring(firstfound + wordtoSearch.Length);
Console.WriteLine(after);
}
}
You can do something like this as well, making it a bit more reusable and able to match multiple instances of the keyword
string input = "A block of text is text that is grouped together in some way, such as with the use of paragraphs or blockquotes on a Web page. Often times, the text takes on the shape of a square or rectangular block";
int buffer = 30; // how much do you want to show before/after
string match = "times";
int location = input.IndexOf(match);
while (location != -1) {
// take buffer before and after:
int start = location - Math.Min (buffer , location); // don't take before start
int end = location + match.Length
+ Math.Min( buffer, input.Length - location - match.Length); // don't take after end
Console.WriteLine("..." + input.Substring(start, end-start) + "...");
location = input.IndexOf(match,location+1);
}
Giving you an output of
...A block of text is text that is gro...
...with the use of paragraphs or blockquotes on a Web page. Often ...
...pe of a square or rectangular block...

How to skip txt file chunks

How do I skip reading the file at the red boxes only to continue reading the file at the blue boxes? What adjustments would I need to make to 'fileReader'?
So far, with the help of SO users, I've been able to successfully skip the first 8 lines (first red box) and read the rest of the file. But now I want to read ONLY the parts indicated in blue.
I'm thinking of making a method for each chunk in blue. Basically start it by skipping first 8 lines of file if its first blue box, about 23 for the next blue box but ending the file reader is where I'm having problems. Simply don't know what to use.
private void button1_Click(object sender, EventArgs e)
{
// Reading/Inputing column values
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] lines = File.ReadAllLines(ofd.FileName).Skip(8).ToArray();
textBox1.Lines = lines;
int[] pos = new int[3] {0, 6, 18}; //setlen&pos to read specific colmn vals
int[] len = new int[3] {6, 12, 28}; // only doing 3 columns right now
foreach (string line in textBox1.Lines)
{
for (int j = 0; j < 3; j++) // 3 columns
{
val[j] = line.Substring(pos[j], len[j]).Trim();
list.Add(val[j]); // column values stored in list
}
}
}
}
Try something like this:
using System.Text.RegularExpressions; //add this using
foreach (string line in lines)
{
string[] tokens = Regex.Split(line.Trim(), " +");
int seq = 0;
DateTime dt;
if(tokens.Length > 0 && int.TryParse(tokens[0], out seq))
{
// parse this line - 1st type
}
else if (tokens.Length > 0 && DateTime.TryParse(tokens[0], out dt))
{
// parse this line - 2nd type
}
// else - don't parse the line
}
The Regex split is handy to break on any spaces till the next token. The Regex " +" means match one or more spaces. It splits when it finds something else. Based on your example, you only want to parse lines that begin with a number or a date, which this should accomplish. Note that I trimmed the line of leading and trailing spaces so that you don't split on any of those and get empty string tokens.
I can see what you want to read anything what:
between line ending with Numerics (possible one line after)
until line starting with 0Total (is that zero, right?);
between line ending with CURREN
until line with 1 as first symbol in the row.
Shouldn't be hard. Read file by line. When (1) or (3) occurs, start generating until (2) or (4) correspondingly.

C# - Addition on a string and replace with new string

If I have a RichTextBox that is loaded from a file containg:
TEXT MORETEXT 10.505 100.994 0
TEXT MORETEXT -5.132 -12.994 90
TEXT MORETEXT 100.001 -8.994 270
and a TextBox that contains whatever the user enters in the textbox. Let's say the user enters "10.005".
My question is, how do I take this value and add it to the 3rd column containing the values 10.505, -5.132, 100.001. Once it is added, I would like to take the value and Replace the old value in the string. SO the updated RichTextBox would look like this.
TEXT MORETEXT 20.510 100.994 0
TEXT MORETEXT 4.873 -12.994 90
TEXT MORETEXT 110.006 -8.994 270
RIGHT NOW I am able to strip the strings from the RichTextBox by using this code:
private void calculateXAndYPlacementTwo()
{
// Reads the lines in the file to format.
var fileReader = File.OpenText(filePath);
// Creates a list for the lines to be stored in.
var fileList = new List<string>();
// Adds each line in the file to the list.
while (true)
{
var line = fileReader.ReadLine();
if (line == null)
break;
fileList.Add(line);
}
// Creates new lists to hold certain matches for each list.
var xyResult = new List<string>();
var xResult = new List<string>();
var yResult = new List<string>();
// Iterate over each line in the file and extract the x and y values
fileList.ForEach(line =>
{
Match xyMatch = Regex.Match(line, #"(?<x>-?\d+\.\d+)\s+(?<y>-?\d+\.\d+)");
if (xyMatch.Success)
{
// grab the x and y values from the regular expression match
String xValue = xyMatch.Groups["x"].Value;
String yValue = xyMatch.Groups["y"].Value;
// add these two values, separated by a space, to the "xyResult" list.
xyResult.Add(String.Join(" ", new[]{ xValue, yValue }));
// Adds the values into the xResult and yResult lists.
xResult.Add(xValue);
yResult.Add(yValue);
// Place the 'X' and 'Y' values into the proper RTB.
xRichTextBox.AppendText(xValue + "\n");
yRichTextBox.AppendText(yValue + "\n");
}
});
}
To get the values in the xRichTextBox looking like:
10.505
-5.132
100.001
and the yRichTextBox looking like:
100.994
-12.994
-8.994
But I do not know how to turn those into values that can have addition used on them...
EDIT:
I have messed around with this some more... I am now using this code (below) to try to accomplish what I need it to do. This is only for the "X" (3rd column).
HOWEVER THIS CODE IS NOT WORKING (it concats the user input to the end of the xRichTextBox instead of mathematically adding it to each line..)
The xDisplacementTextBox is the user input and the xRichTextBox is the stripped values from the main string.
StringBuilder stringBuilder = new StringBuilder();
string[] Lines = xRichTextBox.Text.Split('\n');
double d = double.Parse(xDisplacementTextBox.Text);
for(int i = 0; i < Lines.Length; ++i)
{
string newThing = double.Parse((Lines[i]) + d).ToString();
stringBuilder.AppendLine(newThing);
}
xRichTextBox.Text = stringBuilder.ToString();
This is also not letting me enter in values that have decimals (ie. 50.005)..
Look at double.Parse - as in
double x = double.Parse(xValue);
To expand, and do your work for you...
double d = double.Parse(xDisplacementTextBox.Text);
string[] Lines = xRichTextBox.Text.Split('\n');
for(int i = 0; i < Lines.Length; ++i)
{
Match lineMatch = Regex.Match(lines[i], #"^(?<p>.*)(?<x>-?\d+\.\d+)(?<y>\s+-?\d+\.\d+\s+-?\d+\.\d+)$");
if (lineMatch.Success)
{
double xValue = double.Parse(lineMatch.Groups["x"].Value) + d;
lines[i] = lineMatch.Groups["p"] + xValue + lineMatch.Groups["p"];
}
}
xRichTextBox.Text = string.Join(lines, '\n');
Too many strings and not enough data structures.
This looks like a data structure:
TEXT MORETEXT 10.505 100.994 0
TEXT MORETEXT -5.132 -12.994 90
TEXT MORETEXT 100.001 -8.994 270
So, create a class that holds
"Text" string
"MoreText" string
10.505 - double (let's call this prop1)
100.994 - double
0 - int
I'm speculating on the data values here.
Load the List<> of your class into memory.
Then, apply the text box value to your list of object every time the value changes.
PsuedoCode:
foreach(class c in List<>)
{
c.prop1 = c.prop1 + (double)Textbox.value;
}
Override ToString() in your class and display the object as needed in the rich text box.
Personally I would use a list box to display the objects.

How to calculate the amount that exists in 2 different text files

I have my file names with the name
PPD_EntryDetailRecord_07192010.txt
PPD_EntryDetailRecord_07182010.txt
PPD_EntryDetailRecord_07162010.txt
In that the data will be like
6111111111111111111111111111125000000001111111111111111111111111111111111111111 1
6111111111111111111111111111150000000001111111111111111111111111111111111111111 1
611111111111111111111111111116500000.721111111111111111111111111111111111111111 1
Now I would like to add all those which were in bold and should display the sum...
The best I can make of it:
int start = "61111111111111111111111111111".Length + 1;
int length = "2500000000".Length;
string[] lines = System.IO.File.ReadAllLines(filename);
foreach(string line in lines)
{
string data = line.SubString(start, length);
double number = double.parse(data, CultureInfo.InvariantCulture);
// sum it
}
If you are after the numbers in italic (not bold), and there are *s in the file, you can get the value like this (quick and dirty example code until you confirm the question):
string line = ""; // read a line from the file here
double lineValue = double.Parse(line.Split('*')[1]); // split by "*", get the second element, and parse as a double
You'd loop through all lines in the file and add lineValue to a sum variable.
Hope that helps.

Particular content in richtextbox

I want to display some bold and some simple content in the form so I am using richtextbox.And I have made one file with extension of .rtf.Now I load that file in the richtextbox with use of the Loadfile() function.This works. But I want to display particular content of the file in the richtextbox,like may be first five lines or it may be line no. of six to ten.Then is there any solution ??
It is possible, just not very cleanly. This code uses another RTB to load the file and the clipboard to get the formatted RTF. Beware that it destroys the clipboard content.
using (var helper = new RichTextBox()) {
helper.LoadFile(#"c:\temp\test.rtf");
// Copy line #6
int startRange = helper.GetFirstCharIndexFromLine(5);
int endRange = helper.GetFirstCharIndexFromLine(6);
helper.SelectionStart = startRange;
helper.SelectionLength = endRange - startRange;
helper.Copy();
}
richTextBox1.SelectAll();
richTextBox1.Paste();
This doesn't preserve any formatting, but shows how you could manipulate the Lines array. It looks like the RichTextBox selfishly keeps all RTF codes to itself and only exposes text through Lines:
var fromStart = new string[richTextBox1.Lines.Length - start];
Array.Copy(richTextBox1.Lines, start, fromStart, 0, fromStart.Length);
var lineSet = fromStart.Take(count).ToArray();
richTextBox1.Lines = lineSet;
start and count are passed into this function that selects a set of lines.
Solution using ReadAllLines:
string[] lines = File.ReadAllLines(filename);
int startLine = lines.IndexOf(startMarker);
int endLine = lines.IndexOf(endMarker);
if (startLine == -1 || endLine == -1)
{
// throw some sort of exception - the markers aren't present
}
string[] section = new string[endLine - startLine - 1];
Array.Copy(lines, startLine + 1, section, 0, section.Length);
richTextBox.Rtf = string.Join("\r\n", section);
Solution using ReadAllText:
string text = File.ReadAllText(filename);
int startIndex = text.IndexOf(startMarker);
int endIndex = text.IndexOf(endMarker, startIndex + startMarker.Length);
if (startIndex == -1 || endIndex == -1)
{
// throw some sort of exception - the markers aren't present
}
richTextBox.Rtf = text.Substring(startIndex + startMarker.Length,
endIndex - startIndex - startMarker.Length);
Both of these assume that you really have got a complete RTF document in that section of the file though - you may well find you need additional header text, for example. Also, both assume the file is in UTF-8. I don't know enough about the RTF format to know if that's correct.
Did you tried the Lines property? It allows set / get string array as the RichTextbox content.

Categories

Resources