TextBox is not creating newline when reading text file C# - c#

I have this program that supposed to reads multiple text files on the same folder, in that folder there's 2 text files which are supposed to be read, ok now I have to generate a new TextBox based on the total numbers of text files in that folder.
Main Goal
Load the contents of those files in each textbox
File1.txt contents will be loaded into TextBox1.
File2.txt contents will be loaded into TextBox2.
Content of File1.txt:
Title 1
ABCDEFG
Content of File2.txt:
Title 2
1234567890
The problem
Loading the contents of those files into each TextBoxes works fine, but the problem is that the newline isn't created on the TextBoxes.
Instead I got this on each textboxes:
TextBox 1:
Title 1ABCDEFG
TextBox 2:
Title 21234567890
Do the necessary stuff as soon the program loads:
private void Form1_Load(object sender, EventArgs e) {
flowLayoutPanel1.AutoScroll = true;
var dirs_notes = #"C:\MAIN_LOC\DATA_LOC\";
var count_notes = Directory.GetFiles(dirs_notes,"*.*",SearchOption.AllDirectories).Count();
string setup_path = #"C:\MAIN_LOC\DATA_LOC\";
if(Directory.Exists(setup_path)) {
string[] get_notes = Directory.GetFiles(dirs_notes, "*.txt", SearchOption.AllDirectories);
string[] get_texts = get_notes.Select(x => File.ReadAllText(x)).ToArray();
for(int i=0; i<count_notes; i++) {
int top = 25;
int h_p = 170;
var load_note = new Guna2TextBox() {
Text = "\n" + get_texts[i],
Name = "Note" + i,
Multiline = true,
AcceptsTab = true,
AcceptsReturn = true,
WordWrap = false,
Width = 230,
Height = 145,
BorderRadius = 8,
Font = new Font("Bahnschrift", 13),
ForeColor = Color.White,
FillColor = ColorTranslator.FromHtml("#1E1E1E"),
BorderColor = ColorTranslator.FromHtml("#2C2C2C"),
Location = new Point(450, top)
};
top += h_p;
flowLayoutPanel1.Controls.Add(load_note);
}
} else {
MessageBox.Show("There's problem with loading notes..", "Flow Notes System");
}
}

A fix could be using the Lines property instead of the Text property.
var dirs_notes = #"C:\MAIN_LOC\DATA_LOC\";
// Be sure to count only txt files here...
var count_notes = Directory.GetFiles(dirs_notes,"*.txt",SearchOption.AllDirectories).Count();
string setup_path = #"C:\MAIN_LOC\DATA_LOC\";
if(Directory.Exists(setup_path)) {
string[] get_notes = Directory.GetFiles(dirs_notes, "*.txt", SearchOption.AllDirectories);
var get_texts = get_notes.Select(x => File.ReadLines(x));
for(int i=0; i<count_notes; i++) {
....
var load_note = new Guna2TextBox() {
Lines = "\n" + get_texts[i].ToArray(),
But a better approach is to use this instead:
// No counting here (counting means load all
// files names in a memory array and the get its length
var files = Directory.EnumerateFiles(dirs_notes,"*.txt",SearchOption.AllDirectories)
int i = 1;
// Enumerate files one by one without loading all names in memory
foreach(string file in files) {
int top = 25;
int h_p = 170;
var load_note = new Guna2TextBox() {
// Set the textbox with the current file lines content
// again one by one without loading all texts in memory
Lines = File.ReadLines(file).ToArray(),
Name = "Note" + i,
...
}
i++;
.....
}

Related

fill chart from csv file

I have csv file with data:
1,1671790171,75
0,1671790182,11
1,1671790193,11
0,1671790212,19
1,1671790239,27
0,1671790248,97
1,1671790342,94
0,1671790361,19
1,1671790368,79
0,1671790408,40
1,1671790417,90
0,1671790432,15
I need create application to show chart where first data is "work" or "not work", second data is linuxtimestamp data and time, third data is the number of seconds the process took.
I wrote something like this:
// Use OpenFileDialog to allow the user to select a CSV file
var openFileDialog = new OpenFileDialog
{
Filter = "CSV files (*.csv)|*.csv"
};
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// Clear the chart
chart1.Series.Clear();
// Read the CSV file
using (var reader = new StreamReader(openFileDialog.FileName))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
// Parse the values
var working = values[0] == "1";
var timestamp = long.Parse(values[1]);
var duration = int.Parse(values[2]);
// Convert the Unix timestamp to a DateTime
var date = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime;
// Create a new series in the chart
var series = new System.Windows.Forms.DataVisualization.Charting.Series
{
Name = date.ToString("dd-MM-yyyy HH:mm:ss"),
Color = working ? Color.Red : Color.Green,
BorderColor = Color.Black,
ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Bar,
IsXValueIndexed = false,
XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime
};
series.Points.AddXY(date, duration);
chart1.Series.Add(series);
}
}
// Set the bar width for all series
foreach (var series in chart1.Series)
{
foreach (var point in series.Points)
{
// point.Width = 20;
point.BorderWidth = 0;
}
}
However, I need help with replacing so that on line X there are all occurrences (i.e. each line) with preferably a vertical entry of the date of occurrence, and on line Y there is time of operation (i.e. the last data from each line)

Having problems getting PDF document from text file formatted correctly with GemBox

I am attempting to convert a text file to a pdf using GemBox. I can get the text imported correctly but the font type and size aren't being applied and the sentence spacing seems to be doubled.
This is what I have so far:
public static void CreateDoc(string ebillpath)
{
using (var sr = new StreamReader(ebillpath))
{
var doc = new DocumentModel();
doc.DefaultCharacterFormat.Size = 10;
doc.DefaultCharacterFormat.FontName = "Courier New";
var section = new Section(doc);
doc.Sections.Add(section);
string line;
var clearedtop = false;
while ((line = sr.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line) && !clearedtop)
{
continue;
}
clearedtop = true;
Paragraph paragraph2 = new Paragraph(doc, new Run(doc, line));
section.Blocks.Add(paragraph2);
}
PageSetup pageSetup = new PageSetup(); // section.PageSetup;
var pm = new PageMargins();
pm.Bottom = 36;
pm.Top = 36;
pm.Right = 36;
pm.Left = 36;
pageSetup.PageMargins = pm;
doc.Save(#"d:\temp\test.pdf");
}
}
This text file uses spaces to format the text correctly so I need to set the font to Courier New.
This is an example of what the text file looks like with correct formatting:
And this is what it comes out to look like in pdf form:
Each line seems to be doubled and the font isn't being applied.
Any suggestions?
Try this:
public static void CreateDoc(string ebillpath)
{
DocumentModel doc = new DocumentModel();
CharacterFormat charFormat = doc.DefaultCharacterFormat;
charFormat.Size = 10;
charFormat.FontName = "Courier New";
ParagraphFormat parFormat = doc.DefaultParagraphFormat;
parFormat.SpaceAfter = 0;
parFormat.LineSpacing = 1;
// It seems you want to skip first line with 'clearedtop'.
// So maybe you could just use this instead.
string text = string.Concat(File.ReadLines(ebillpath).Skip(1));
doc.Content.LoadText(text);
Section section = doc.Sections[0];
PageMargins margins = section.PageSetup.PageMargins;
margins.Bottom = 36;
margins.Top = 36;
margins.Right = 36;
margins.Left = 36;
doc.Save(#"d:\temp\test.pdf");
}
I hope it helps.

how I can copy the text in a specified field, without mention the line number

I have the next code :
private void button1_Click_1(object sender, EventArgs e)
{
string path = AppDomain.CurrentDomain.BaseDirectory.ToString();
var link = File.ReadLines(path + "test.txt").ToArray();
var lines = File.ReadAllLines(path + "test2.txt");
foreach (var txt in link )
{
if (txt.Contains("Output="))
{
var outputPath = txt.Split('=')[1];
if (File.Exists(path + "test2.txt"))
{
var modifiedLines = lines.Select(line =>
{
if (line.StartsWith("outlog=\""))
{
return string.Format("outlog=\"{0}\"", outputPath);
}
else
{
return line;
}
});
File.WriteAllLines(path+ "test2.txt", modifiedLines);
}
}
}
With this code I whan to copy what is after equel from Output="C:\temp\out.log"(who is in test.txt), after equal in outlog=(who is in test2.txt).
How I can copy the text who exists in one text file test.txt, in a specified location from a second field test2.txt, without mentioned the line number ?
Here I put just a row, but in my files text I have many rows, but I think I make this to work, I handle with another rows.
test.txt have
Licfile="C:\temp\lic.lic"
Output="C:\temp\out.log"
Title="name"
test2.txt have
outlog=
license=
lmgr_files=
license_path=
and after runing the code the test2.txt I want to looks like this:
outlog="C:\temp\out.log"
license_path="C:\temp\lic.lic"
lmgr_files=false
license=true
I am confused about your problem but i just want to try to give you an opinion. I hope it may be help you. But line numbers are really important for these problem.
String[] arrayOld = File.ReadAllLines(#"C:\test.txt");
String[] arrayNew = new string[arrayOld.Length];
if (arrayOld[0].Contains("Licfile=")) // If statements could be more
{
Array.Copy(arrayOld,0,arrayNew,0,2); // How many line will add
}
for (int i = 0; i < 2; i++)
{
File.AppendAllText(#"D:\test2.txt", arrayNew[i] + Environment.NewLine); // It'll add all lines
}
P.S.: Don't forget to add strings like lineOne = "outlog=" + locString; etc.

Span Two Columns When Dynamically Adding Controls

I have an ASP.NET web application. This application renders out glossary type items, similar to the following:
This goes through all the letters in the alphabet for items. I am rendering this out and appending it directly to a Controls collection in a Server Control using the following:
List<char> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray().ToList();
foreach (char c in alpha)
{
Label lblAlphaCharacter = new Label();
lblAlphaCharacter.Font.Size = 24;
lblAlphaCharacter.Font.Bold = true;
lblAlphaCharacter.Text = c.ToString(CultureInfo.InvariantCulture);
Controls.Add(lblAlphaCharacter);
Controls.Add(new LiteralControl("<p>"));
FilterOnAlphaCharacter(this, Page, c);
Controls.Add(new LiteralControl("<p>"));
}
private static void FilterOnAlphaCharacter(Control control, Page page, char character)
{
foreach (List<Things> item in items)
{
string title = item.Title;
string description = item.Definition;
HyperLink link = new HyperLink();
link.Text = title;
control.Controls.Add(link);
Label lblDescription = new Label();
lblDescription.Text = string.Format(" - {0}", description);
control.Controls.Add(lblDescription);
}
}
}
I am trying to, depending on the content, equally split this, so that it looks like this:
This can have different amounts of items. So in reality, there could be 25 entries under "A", and perhaps 1 under "Z". The above is just an example, it goes through all letters A-Z. The expected result would be based on the amount of content, it would equally split between two columns. I have to do this server-side (I was thinking using Table or HtmlTable and related objects).
Howe would you implement a solution for splitting the content equally in a Table or the likes (sort of indifferent on approach).
try this:
//it shows the number of line that inserting during the process
private int _inserteditemCount;
//its number of items in each column
private int _itemsCount;
//line height use for determine paragraph line height
private const string Lineheight = "30px";
protected void Page_Load(object sender, EventArgs e)
{
_inserteditemCount = 0;
var alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
//you can do this query in data access layer
var listCountcount = new Thingsclass().GetThings().Count;
//Count of rows on dictionary + number of leters
_itemsCount = (listCountcount + alpha.Count()) / 2;
var leftdiv = new HtmlGenericControl("div");
var rightdiv = new HtmlGenericControl("div");
//you can change this styles
leftdiv.Style.Add("display", "inline-block");
leftdiv.Style.Add("width", "50%");
leftdiv.Style.Add("float", "Left");
rightdiv.Style.Add("display", "inline-block");
rightdiv.Style.Add("float", "right");
rightdiv.Style.Add("width", "50%");
foreach (var c in alpha)
{
var lblAlphaCharacter = new Label();
lblAlphaCharacter.Font.Size = 24;
lblAlphaCharacter.Font.Bold = true;
lblAlphaCharacter.Text = c.ToString(CultureInfo.InvariantCulture);
var control = _inserteditemCount <= _itemsCount ? leftdiv : rightdiv;
var paragraph = new HtmlGenericControl("p");
paragraph.Style.Add("line-height", Lineheight);
paragraph.Controls.Add(lblAlphaCharacter);
control.Controls.Add(paragraph);
FilterOnAlphaCharacter(leftdiv, rightdiv, c.ToString());
_inserteditemCount++;
}
Panel1.Controls.Add(leftdiv);
Panel1.Controls.Add(rightdiv);
}
private void FilterOnAlphaCharacter(Control leftctr, Control rightctr, string character)
{
//you can do this query in data access layer
var items = new Thingsclass().GetThings().Where(c => c.chara.ToLower().Equals(character.ToLower()));
foreach (var item in items)
{
var paragraph = new HtmlGenericControl("p");
paragraph.Style.Add("line-height", Lineheight);
var control = _inserteditemCount <= _itemsCount ? leftctr : rightctr;
var title = item.Title;
var description = item.Description;
var link = new HyperLink { Text = title };
paragraph.Controls.Add(link);
var lblDescription = new Label { Text = string.Format(" - {0}", description) };
paragraph.Controls.Add(lblDescription);
_inserteditemCount++;
control.Controls.Add(paragraph);
}
}

Sort Microsoft.Office.Interop.Word in C#

I use Microsoft.Office.Interop.Word to get words from Word file and then I populate it into a table layout panel. Unfortunately, the words displayed at the table layout panel are not following exact sequence as in the Word file.
How to fix this?
// Open a doc file.
Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
Document d ocument = application.Documents.Open(txtUploadedPathToken.Text);
// Loop through all words in the document.
int count = document.Words.Count;
for (int i = 1; i <= count; i++)
{
// Write the word.
string text = document.Words[i].Text;
//Console.WriteLine("Word {0} = {1}", i, text);
tableLayoutPanel2.Controls.Add(new Label() { Text = text, Anchor = AnchorStyles.Left, AutoSize = true}, 0, 0);
}
Your word document reading code seems OK. but you may need to change how you add items to panel. Since you add new items to same position (0,0) it may give incorrect order.
foreach (Microsoft.Office.Interop.Word.Range range in document.Words)
{
string text = range.Text;
tableLayoutPanel2.Controls.Add(new Label() { Text = text, Anchor = AnchorStyles.Left, AutoSize = true});
}

Categories