C# Second text box filling out with random names - c#

this is my code and I also have a snippet in the link below of what my program looks like when run. My problem is with the second text box and that it is filling out with random gibberish. My first text box is working perfectly it is picking a random first name from my text file and putting it into the text box. I dont understand what my second text file isnt doing the same'?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
{
Random r = new Random();
int currentLinefirst = 1;
string pick = null;
foreach (string line in File.ReadLines("C:\\Users\\Admin\\Desktop\\C# Programs\\WindowsFormsApplication5\\WindowsFormsApplication5\\First Names.txt"))
{
if (r.Next(currentLinefirst) == 0)
{
pick = line;
}
++currentLinefirst;
}
textBox1.Text = pick;
}
Random n = new Random();
int currentLinelast = 1;
string pick2 = null;
foreach (string line1 in File.ReadLines("C:\\Users\\Admin\\Desktop\\C# Programs\\WindowsFormsApplication5\\WindowsFormsApplication5\\Last Names.txt"))
{
if (n.Next(currentLinelast) == 0)
{
pick2 = line1;
}
++currentLinelast;
}
textBox2.Text = pick2;
}
}
}
i am getting this output of random numbers in textbox

It is probably because your second file contains a line with multiple names. When you call File.ReadLines, it will return an array of string on each line
Try separating you last names with line feeds.

To save the text to a text file use
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\Admin\Desktop\test.txt", true))
{
file.WriteLine("First Name: {0} Last Name: {1}", textBox1.Text, textBox2.Text);
}
{0} and {1} are placeholders
if the file is does not exist it will create a new file to the given path and if the file already exists then it will add new entry to the file.

You can try this:
string firstname = textBox1.Text;
string lastname = textBox2.Text;
Byte[] info = new UTF8Encoding(true).GetBytes(firstname + lastname);
string FilePath = yourpath + DateTime.Now.ToString("dd-MMM-yyyy") + ".txt";
using (FileStream fs = File.Create(FilePath))
{fs.Write(info, 0, info.Length);}

Related

How to delete from one row to the end of a text file in c#?

I have a text file (filename.txt) and I want to delete everything in this file from a special row number to the end of the text file.
How can I do this?
Is it even possible?
P.S.:
The number of the line is not constant.
It depends on the value of another variable in my code.
You can do the following:
Read the count of lines which you need.
Delete the file.
Write your lines to a newly created file with the same path and name.
Below is an example of the code:
using System.IO;
using System.Collections.Generic;
namespace ConsoleApp3
{
public class Program
{
static void Main(string[] args)
{
int lineNumber = 4;
string filePath = #"C:\Users\Admin\Desktop\test - Copy.txt";
List<string> lines = new List<string>();
using (TextReader tr = new StreamReader(filePath))
{
int i = 0;
while(i!=lineNumber)
{
lines.Add(tr.ReadLine());
i++;
}
}
File.Delete(filePath);
File.WriteAllLines(filePath,lines);
}
}
}

C# Delete line from .txt extension with a changing filename

I am currently trying to make an .exe in c# that I can drag and drop a .txt file onto to remove lines of text that contain the keywords "CM" and/or "Filling". It must be able to overwrite the existing data so there are no new files created. The filename is different every time except for the extension. The data is tab delimited if that has any bearing. I'm aware that there are similar questions to this but I haven't managed to adapt them to suit my needs. Also, I'm very new to this and I've been trying for about a week with no luck.
if (args.Length == 0)
return; // return if no file was dragged onto exe
string text = File.ReadAllText("*.txt");
text = text.Replace("cm", "");
string path = Path.GetDirectoryName(args[0])
+ Path.DirectorySeparatorChar
+ Path.GetFileNameWithoutExtension(args[0])
+ "_unwrapped" + Path.GetExtension(args[0]);
File.WriteAllText("*.txt", text);
\\attempt 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
string concrete = "CM";
string line;
using (StreamReader reader = new StreamReader(#"C:\\Users\drocc_000\Desktop\1611AN24T99-041805221704.txt"))
{
using (StreamWriter writer = new StreamWriter(#"C:\\Users\drocc_000\Desktop\1611AN24T99-041805221704NEW.txt"))
{
while ((line = reader.ReadLine()) != null)
{
// if (String.Compare(line, yourName) == 0)
// continue;
writer.WriteLine(line.Replace(concrete, ""));
}
}
}
\\attempt 2
Thanks for your time.
Regards,
Danny
You can create a console application with the code below and then drag and drop your text file into the .exe file without opening it.
class Program
{
static void Main(string[] args)
{
if (args.Length > 0 && File.Exists(args[0]))
{
string path = args[0];
EditFile(new List<string>() { "CM", "Filling" }, path);
}
Console.Read();
}
public static void EditFile(List<string> keyWords, string filename)
{
List<string> lines = new List<string>();
using (StreamReader sr = new StreamReader(filename))
{
while (sr.Peek() >= 0)
{
lines.Add(sr.ReadLine());
}
sr.Close();
}
int removedLinesCount = 0;
bool writeline;
using (StreamWriter sw = new StreamWriter(filename))
{
foreach (var line in lines)
{
writeline = true;
foreach (var str in keyWords)
{
if (line.Contains(str))
{
writeline = false;
removedLinesCount++;
break;
}
}
if (writeline)
sw.WriteLine(line);
}
Console.WriteLine(removedLinesCount + " lines removed from the file " + filename);
sw.Close();
}
}
}
Something like this?
using System;
using System.IO;
using System.Linq;
namespace ConsoleApp1
{
internal static class Program
{
private static void Main(string[] args)
{
try
{
// Get the filename from the applications arguments
string filename = args[0];
// Read in all lines in the file.
var linesInFile = File.ReadLines(filename);
// Filter out the lines we don't need.
var linesToKeep = linesInFile.Where(line => !line.Contains("CM") && !line.Contains("Filling")).ToArray();
// Overwrite the file.
File.WriteAllLines(filename, linesToKeep);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

Get the first and last cell in each row of CSV file using C#

I have a csv file like this:
1,2,3,4,5
6,7,8
9,10
How can I get the first and last cell to get the file like this:
1,5
6,8
9,10
This is a sample code that you may use to achieve your goal:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FirstLast
{
class Program
{
static void Main(string[] args)
{
String file = "C:\\samplec#programs\\FirstLast\\FirstLast\\bin\\Debug\\Test.csv";
using (StreamReader SR = new StreamReader(file))
{
while (!SR.EndOfStream) //best way to do it
{
//read a line of our file and split it into its separate values
var CSValues = SR.ReadLine().Split(',');
String first = CSValues.First();
String last = CSValues.Last();
Console.WriteLine("First val: " + first + " , Last val: " + last);
}
}
Console.ReadLine();
}
}
}
This is a simple sample in console, I believe you can understand from here. Take note of
String first = CSValues.First();
String last = CSValues.Last();

Removing a row from a csv file when it is selected from a comboBox and a button pressed

I recently asked about a piece of code to hold data for my trading cards. I have a file that contains the overall list of the cards in a CSV file. I was wondering if there was any way to remove a row from the CSV file when the card number is selected and the submit button pressed. The code I currently have is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace YuGiOh_Card_List
{
public partial class frmAddLOB : Form
{
List<string> cardNo = new List<string>();
List<string> cardName = new List<string>();
List<string> cardRarity = new List<string>();
List<string> cardType = new List<string>();
public frmAddLOB()
{
InitializeComponent();
StreamReader reader = File.OpenText("..\\Debug\\lobList.csv");
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
cardNo.Add(values[0]);
cardName.Add(values[1]);
cardRarity.Add(values[2]);
cardType.Add(values[3]);
cboCardNo.Items.Add(values[0]);
}
reader.Close();
}
private void cboCardNo_SelectedIndexChanged(object sender, EventArgs e)
{
lblCardNoFinal.Text = cardNo[cboCardNo.SelectedIndex];
lblCardNameFinal.Text = cardName[cboCardNo.SelectedIndex];
lblCardRarityFinal.Text = cardRarity[cboCardNo.SelectedIndex];
lblCardTypeFinal.Text = cardType[cboCardNo.SelectedIndex];
}
private void btnAdd_Click(object sender, EventArgs e)
{
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text);
Global.card.Add(card);
File.AppendAllLines(file, new[] { card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter + card.CardType });
MessageBox.Show("Card Added");
}
}
}
So I want the row to be removed from the 'loblist.csv' and added to the LOB file (which it is currently doing). Thanks
This should work (untested). Unfortunately, there's no classes/methods available in .Net (AFAIK) for in-place editing of text files (it makes sense when you think about it I guess). Disclaimer - there are much cleaner ways to do what you're aiming for here functionality-wise, including the approach described by Plutonix above:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace YuGiOh_Card_List
{
public partial class frmAddLOB : Form
{
List<string> cardNo = new List<string>();
List<string> cardName = new List<string>();
List<string> cardRarity = new List<string>();
List<string> cardType = new List<string>();
List<string> Lines = new List<string>();
public frmAddLOB()
{
InitializeComponent();
StreamReader reader = File.OpenText("..\\Debug\\lobList.csv");
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
Lines.Add(line);
cardNo.Add(values[0]);
cardName.Add(values[1]);
cardRarity.Add(values[2]);
cardType.Add(values[3]);
cboCardNo.Items.Add(values[0]);
}
reader.Close();
}
private void cboCardNo_SelectedIndexChanged(object sender, EventArgs e)
{
lblCardNoFinal.Text = cardNo[cboCardNo.SelectedIndex];
lblCardNameFinal.Text = cardName[cboCardNo.SelectedIndex];
lblCardRarityFinal.Text = cardRarity[cboCardNo.SelectedIndex];
lblCardTypeFinal.Text = cardType[cboCardNo.SelectedIndex];
}
private void btnAdd_Click(object sender, EventArgs e)
{
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text,
lblCardTypeFinal.Text);
Global.card.Add(card);
var newLine = card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter +
card.CardType;
File.AppendAllLines(file,
new string [] {newLine});
if (Lines.Contains(newLine))
{
Lines.Remove(newLine);
File.WriteAllLines("..\\Debug\\lobList.csv", Lines);
}
MessageBox.Show("Card Added");
}
}
}

Error while opening csv file in C#

I'm stuck here while opening and reading csv file in c# program. Ive just started working upon ILNumerics to display 3D matrix graph, but the Exception rises with
"Could not find file 'C:\Users\asd\Documents\Visual Studio 2013\Projects\matrixgraph\martix\bin\Debug\stats.csv'."
Please help me out!
Below is the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using ILNumerics;
using ILNumerics.Drawing;
using ILNumerics.Drawing.Plotting;
namespace martix
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ilPanel1_Load(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
string path = #"C:\Users\asd\Documents\Visual Studio 2013\Projects\matrixgraph\martix\bin\Debug\stats.csv";
StreamReader sr = new StreamReader(File.Open(path, FileMode.Open));
string dataLines = string.Empty;
while (sr.Peek() != -1)
dataLines += sr.ReadLine().Replace(";", ",") + "\n";
sr.Close();
dataLines = dataLines.Trim('\n');
//Convert the data-string into an ILArray
ILArray<int> AN = ILMath.csvread<int>(dataLines);
//Create a new scene, which is the base for our graph
var scene = new ILScene();
using (ILScope.Enter())
{
//Convert all data points to float
ILArray<float> A = ILMath.tosingle(AN);
//Add a plot to the scene and configure it
scene.Add(new ILPlotCube
{
//Render in 3D
TwoDMode = false,
//Add 3 axes
Axes =
{
XAxis =
{
Label = { Text = "Price in $" },
GridMajor =
{
DashStyle = DashStyle.Dashed,
Color = Color.DarkGray,
Width = 1
}
},
YAxis =
{
Label = { Text = "Rating count" },
GridMajor =
{
DashStyle = DashStyle.Dashed,
Color = Color.DarkGray,
Width = 1
}
},
ZAxis =
{
Label = { Text = "Download count" }
}
},
//Add the data points
Children = {
new ILPoints {
Positions = A
},
},
//Set start rotation for 3D rendered graph
Rotation = Matrix4.Rotation(new Vector3(1, 1, 1), 0.5f)
});
}
//Add the scene to the ILPanel
ilPanel1.Scene = scene;
}
}
}
It may be the spaces you have in the path. Nevermind, you're using verbatim string.
Are you sure that path is accessible and is not a networked mapped path? Can you move your file temporarily? It really seems that you don't have access to that path.
Also you should try doing the following to pinpoint the issue:
System.IO.FileInfo fi = null;
try
{
fi = new System.IO.FileInfo(path);
}
catch (ArgumentException) {... }
catch (System.IO.PathTooLongException) {... }
catch (NotSupportedException) {... }
if (ReferenceEquals(fi, null))
{
...
// file name is not valid
}
else
{
...
// file name is valid... May check for existence by calling fi.Exists.
}
EDIT:
use System.IO.Directory.GetFiles to list the exact names of the files in that folder, it may be that the file name is different (stats.csv.csv) and window explorer is hiding the extension.
Got the solution while trying. I created the csv file programatically and this time it read the file.
Just added the few line before the path and modified the path.
StringBuilder csv = new StringBuilder();
csv.AppendLine("112,113,222");
string csvpath = #"C:\\stats\xyz.csv";
File.AppendAllText(csvpath,csv.ToString());
string path = #"C:\stats\xyz.csv";
And thats it. Anyways Thanks for helping :)

Categories