I believe the creating the file finished. I am having issues with saving to a file. What I am supposed to do is create the file initially then fill out the form and have it save to that file and separate them by commas in the file so that in my next assignment I can create a form to read the file and have that fill in the form and split by those commas and fill into text boxes.
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 FileExercise
{
public partial class frmscout : Form
{
private StreamWriter fileWriter;
public frmscout()
{
InitializeComponent();
btnsave.Enabled = false;
}
private void clickclear(object sender, EventArgs e)
{
tb40.Clear();
tbheight.Clear();
tbname.Clear();
tbposition.Clear();
tbreps.Clear();
tbverticle.Clear();
}
private void clickexit(object sender, EventArgs e)
{
Application.Exit();
}
private void clickselect(object sender, EventArgs e)
{
DialogResult result;
string fileName;
using (SaveFileDialog fileChooser = new SaveFileDialog())
{
fileChooser.CheckFileExists = false;
result = fileChooser.ShowDialog();
fileName = fileChooser.FileName;
}
if (result == DialogResult.OK)
{
if (fileName == string.Empty)
{
MessageBox.Show("Invalid File Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
try
{
FileStream flstrm = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
fileWriter = new StreamWriter( flstrm );
btnsave.Enabled = true;
btnopen.Enabled = false;
}
catch( IOException )
{enter code here
MessageBox.Show("Error opening file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
//FileStream outfile = new FileStream(fileName, FileMode.Append, FileAccess.Write);
}
private void clicksave(object sender, EventArgs e)
{
string[] values = new string[6];
values[0] = tbname.Text;
values[1] = tbheight.Text;
values[2] = tb40.Text;
values[3] = tbposition.Text;
values[4] = tbreps.Text;
values[5] = tbverticle.Text;
//}
}
}
}
you can do as below
private void clicksave(object sender, EventArgs e)
{
string[] values = new string[6];
values[0] = tbname.Text;
values[1] = tbheight.Text;
values[2] = tb40.Text;
values[3] = tbposition.Text;
values[4] = tbreps.Text;
values[5] = tbverticle.Text;
// you can get file name from `ShowDialog`,
//assume that file name is "filename.txt" then
System.IO.File.WriteAllLines("filename.txt",values);
}
You're creating a new instance of StreamWriter, and gathering your data onClick of the Save button, but nowhere are you calling StreamWriter.Write() or StreamWriter.WriteLine(). You need to insert at least one of those, as appropriate into your code, most likely in the clicksave function.
EDIT:
For example:
private void clicksave(object sender, EventArgs e)
{
string[] values = new string[6];
values[0] = tbname.Text;
values[1] = tbheight.Text;
values[2] = tb40.Text;
values[3] = tbposition.Text;
values[4] = tbreps.Text;
values[5] = tbverticle.Text;
fileWriter.WriteLine(String.Join(",",values));
fileWriter.Flush();
fileWriter.Close();
//}
}
Private void clicksave(object sender, EventArgs e)
{
string[] values = new string[6];
values[0] = tbname.Text;
values[1] = tbheight.Text;
values[2] = tb40.Text;
values[3] = tbposition.Text;
values[4] = tbreps.Text;
values[5] = tbverticle.Text;
fileWriter.WriteLine(String.Join(",",values));
fileWriter.Flush();
fileWriter.Close();
}
for joining of the string you can refer to the below link....as this is reference from Adrian Code..
http://www.dotnetperls.com/string-join
Related
I'll try to add as much information as needed, please tell me if you need any extra info that I haven't added and I'll do my best to provide it.
The basics of my problem is that whenenver I press a button, it will grab the file I select and save it to a text file. This works fine and I can save as many files as needed. The problem lies in the listbox of my listbox. My app is a soundboard, and I want filenames with their hotkeys to be displayed on the listbox which almost works fine. On loading the application the listbox will take all saved files and display them accordingly once and on adding a file, the file will be added to the listbox and it will be saved. As I said this almost works because for some reason unknown to me, you have to click the listbox for it to add the content. My code is as follows:
public partial class Form1 : Form
{
public int getNumberOfSongs()
{
using (Stream stream = File.Open(#"Sounds.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = null;
for (int i = 0; i < 1; ++i)
{
line = reader.ReadLine();
int ine = Int32.Parse(line);
ine = ine + 1;
return ine;
}
}
}
return 8;
//This is only here so it doesn't give me an error, it is never used
}
public void fineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void addFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "WAV files (*.wav)|*.wav";
openFileDialog.DefaultExt = ".wav";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
string filePath = openFileDialog.FileName;
songToAdd = filePath;
string control = filePath + "§modifier§hotkey";
string savePath = #"Sounds.txt";
int bruh = getNumberOfSongs();
fineChanger(control, savePath, bruh);
string bru = bruh.ToString();
fineChanger(bru, savePath, 0);
add = true;
}
}
public bool add = false;
public string songToAdd;
public bool load = true;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
addFile();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (load == true)
{
listBox1.DataSource = File.ReadAllLines(#"Sounds.txt");
load = false;
}
if(add == true)
{
listBox1.Items.Add(songToAdd);
add = false;
}
}
}
P.S. I'm still a novice at windows forms and this app is still nowhere near done.
Instead of adding the items in SelectedIndexChanged I added them in outside. I load the saved songs in Form1_Load and I open/save the loaded files in the addFile() function.
Edited 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 System.Media;
using System.Security.Cryptography.X509Certificates;
using System.Runtime;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;
using System.Diagnostics;
namespace SoundBoard
{
public partial class Form1 : Form
{
public int getNumberOfSongs()
{
using (Stream stream = File.Open(#"Sounds.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = null;
for (int i = 0; i < 1; ++i)
{
line = reader.ReadLine();
int ine = Int32.Parse(line);
ine = ine + 1;
return ine;
}
}
}
return 8;
//This is only here so it doesn't give me an error, it is never used
}
public bool load = true;
public void fineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void addFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "WAV files (*.wav)|*.wav";
openFileDialog.DefaultExt = ".wav";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
string filePath = openFileDialog.FileName;
string control = filePath + "§modifier§hotkey";
string savePath = #"Sounds.txt";
int bruh = getNumberOfSongs();
fineChanger(control, savePath, bruh);
string bru = bruh.ToString();
fineChanger(bru, savePath, 0);
listBox1.Items.Add(filePath);
}
}
public bool loada = true;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
addFile();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
if (loada == true)
{
listBox1.Items.Add(File.ReadAllLines(#"Sounds.txt"));
loada = false;
}
}
}
}
am new to c#,Here am trying to read multiple txt files with its contents at once, then using textbox to collect all the txt content, after collecting the content then I will save all the content back into once txt file. below is my code, pls help out.
Here is the interface of the app
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 FileSaver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel2_Paint(object sender, PaintEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
//File 004: Save the File in System Temporary path
private void button2_Click(object sender, EventArgs e)
{
if (txtFileContent.Visible == true)
{
SaveFile(Path.GetTempPath());
}
else
MessageBox.Show("This form saves only text files");
}
//File 001: Use File open dialog to get the file name
private void btn_File_Open_Click(object sender, EventArgs e)
{
List<String> MyStream = new List<string>();
string ext = "";
this.dlgFileOpen.Filter = "Text Files(*.txt) | *.txt";
this.dlgFileOpen.Multiselect = true;
if (dlgFileOpen.ShowDialog() == DialogResult.OK)
{
try
{
StringBuilder stbuilder = new StringBuilder();
foreach (var files in dlgFileOpen.SafeFileNames )
{
MyStream.Add(files + "\n");
Console.WriteLine();
}
foreach (var item in MyStream)
{
stbuilder.Append(item );
}
txtSelectedFile.Text = stbuilder.ToString() ;
ext = Path.GetExtension(dlgFileOpen.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
if (ext == ".txt")
{
//003: The extension is txt. Read the file and display the content
txtFileContent.Visible = true;
FileStream filestream = new FileStream(dlgFileOpen.FileName, FileMode.Open);
StreamReader streamReader = new StreamReader(filestream);
while (streamReader.EndOfStream != true)
{
txtFileContent.AppendText(streamReader.ReadLine());
txtFileContent.AppendText(Environment.NewLine);
}
streamReader.Close();
}
}
}
private void txtSelectedFile_TextChanged(object sender, EventArgs e)
{
}
//File 002: Use the Path object to determine the selected file has the
// required extension.
private void dlgFileOpen_FileOk(object sender, CancelEventArgs e)
{
string Required_Ext = ".txt ";
string selected_ext = Path.GetExtension(dlgFileOpen.FileName);
int index = Required_Ext.IndexOf(selected_ext);
//002: Inform the user to select correct extension
if (index < 0)
{
MessageBox.Show("Extension Maaaan... Extension! Open only txt or bmp or jpg");
e.Cancel = true;
}
}
private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
{
}
private void SaveFile_Click(object sender, EventArgs e)
{
//001: Setup the Folder dialog properties before the display
string selected_path = "";
dlgFolder.Description = "Select a Folder for Saving the text file";
dlgFolder.RootFolder = Environment.SpecialFolder.MyComputer;
//002: Display the dialog for folder selection
if (dlgFolder.ShowDialog() == DialogResult.OK)
{
selected_path = dlgFolder.SelectedPath;
if (string.IsNullOrEmpty(selected_path) == true)
{
MessageBox.Show("Unable to save. No Folder Selected.");
return;
}
}
//003: Perform the File saving operation. Make sure text file is displayed before saving.
if (txtFileContent.Visible == true)
{
SaveFile(selected_path);
}
else
MessageBox.Show("This form saves only text files");
}
public void SaveFile(string selected_path)
{
string Save_File;
if (selected_path.Length > 3)
Save_File = selected_path + "\\" + txtSaveFile.Text + ".txt";
else
Save_File = selected_path + txtSaveFile.Text + ".txt";
FileStream fstream = new FileStream(Save_File, FileMode.CreateNew);
StreamWriter writer = new StreamWriter(fstream);
writer.Write(txtFileContent.Text);
lblSavedLocation.Text = "Text File Saved in " + Save_File;
writer.Close();
}
private void txtSaveFile_TextChanged(object sender, EventArgs e)
{
}
}
}
Try this out. I stripped out all the the code i felt unnecessary for your problem:
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 FileSaver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel2_Paint(object sender, PaintEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
//File 004: Save the File in System Temporary path
private void button2_Click(object sender, EventArgs e)
{
if (txtFileContent.Visible == true)
{
SaveFile(Path.GetTempPath());
}
else
MessageBox.Show("This form saves only text files");
}
//File 001: Use File open dialog to get the file name
private void btn_File_Open_Click(object sender, EventArgs e)
{
this.dlgFileOpen.Filter = "Text Files(*.txt) | *.txt";
this.dlgFileOpen.Multiselect = true;
if (dlgFileOpen.ShowDialog() == DialogResult.OK)
{
var stBuilder = new StringBuilder();
foreach (var fileName in dlgFileOPen.FileNames)
{
stBuilder.AppendLine(File.ReadAllText(fileName));
}
txtFileContent.Text = stBuilder.ToString();
}
}
private void txtSelectedFile_TextChanged(object sender, EventArgs e)
{
}
//File 002: Use the Path object to determine the selected file has the
// required extension.
private void dlgFileOpen_FileOk(object sender, CancelEventArgs e)
{
}
private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
{
}
private void SaveFile_Click(object sender, EventArgs e)
{
//001: Setup the Folder dialog properties before the display
string selected_path = "";
dlgFolder.Description = "Select a Folder for Saving the text file";
dlgFolder.RootFolder = Environment.SpecialFolder.MyComputer;
//002: Display the dialog for folder selection
if (dlgFolder.ShowDialog() == DialogResult.OK)
{
selected_path = dlgFolder.SelectedPath;
if (string.IsNullOrEmpty(selected_path) == true)
{
MessageBox.Show("Unable to save. No Folder Selected.");
return;
}
}
//003: Perform the File saving operation. Make sure text file is displayed before saving.
if (txtFileContent.Visible == true)
{
SaveFile(selected_path);
}
else
MessageBox.Show("This form saves only text files");
}
public void SaveFile(string selected_path)
{
string Save_File;
if (selected_path.Length > 3)
Save_File = selected_path + "\\" + txtSaveFile.Text + ".txt";
else
Save_File = selected_path + txtSaveFile.Text + ".txt";
File.WriteAllText(Save_File, txtFileContent.Text);
lblSavedLocation.Text = "Text File Saved in " + Save_File;
}
private void txtSaveFile_TextChanged(object sender, EventArgs e)
{
}
}
}
All looks good, except for the reading part, it can be done in a much easier way....
StringBuilder stbuilder = new StringBuilder();
foreach (var filePath in dlgFileOpen.FileNames)
{
StreamReader sr = new StreamReader(filePath);
stbuilder.Append(sr.ReadToEnd());
sr.Close();
//Or Much faster you can use
stbuilder.Append(File.ReadAllText(filePath));
stbuilder.Append(Environment.NewLine);
stbuilder.Append(Environment.NewLine);
txtFileContent.Text = stbuilder.ToString();
}
This question already has answers here:
File being used by another process after using File.Create()
(11 answers)
Closed 6 years ago.
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 Newtonsoft.Json;
namespace Youtube_Player
{
public partial class Authentication : Form
{
public static string AuthenticationApplicationDirectory;
public static string AuthenticationFileName = "Authentication.txt";
StreamWriter w;
public static bool formclosed = false;
static Authentication()
{
AuthenticationApplicationDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "Authentication";
if (!Directory.Exists(AuthenticationApplicationDirectory))
{
Directory.CreateDirectory(AuthenticationApplicationDirectory);
}
AuthenticationFileName = Path.Combine(AuthenticationApplicationDirectory, AuthenticationFileName);
if (!File.Exists(AuthenticationFileName))
File.Create(AuthenticationFileName);
}
public Authentication()
{
InitializeComponent();
cTextBox1.Text = Form1.AuthenticationValues.ApiKey;
cTextBox2.Text = Form1.AuthenticationValues.UserId;
cTextBox3.Text = Form1.AuthenticationValues.JsonFileDirectory;
label1.Visible = false;
button1.Enabled = false;
button4.Enabled = false;
cTextBox2.WaterMarkForeColor = Color.Blue;
cTextBox3.WaterMarkForeColor = Color.Green;
cTextBox2.WaterMarkActiveForeColor = Color.Blue;
cTextBox3.WaterMarkActiveForeColor = Color.Green;
cTextBox1.ForeColor = Color.Red;
cTextBox2.ForeColor = Color.Blue;
cTextBox3.ForeColor = Color.Green;
cTextBox1.WaterMark = "Enter Api Key";
cTextBox2.WaterMark = "Enter Email Account";
cTextBox3.WaterMark = "Browse To The Json File Location";
}
private void Authentication_Load(object sender, EventArgs e)
{
}
private void cTextBox1_TextChanged(object sender, EventArgs e)
{
if (cTextBox1.Text != "Enter Api Key" && cTextBox1.Text != "")
{
button1.Enabled = true;
}
else
{
button1.Enabled = false;
}
}
private void cTextBox2_TextChanged(object sender, EventArgs e)
{
if (cTextBox2.Text != "Enter Email Account" && cTextBox2.Text != "")
{
button4.Enabled = true;
}
else
{
button4.Enabled = false;
}
}
private void cTextBox3_TextChanged(object sender, EventArgs e)
{
if (cTextBox3.Text != "Browse To The Json File Location" && cTextBox3.Text != "")
button6.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Confirmed";
button1.Enabled = false;
label1.Text = "Updating Settings File";
label1.Visible = true;
if (label1.Visible == true)
{
button6.Enabled = false;
button4.Enabled = false;
button1.Enabled = false;
}
FileInfo fi = new FileInfo(AuthenticationFileName);
if (fi.Length == 0)
{
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("Api" + "=" + cTextBox1.Text);
w.Close();
}
else
{
w = new StreamWriter(AuthenticationFileName);
w.WriteLine("Api" + "=" + cTextBox1.Text);
w.Close();
}
timer1.Start();
}
private void button4_Click(object sender, EventArgs e)
{
button4.Enabled = false;
label1.Text = "Updating Settings File";
label1.Visible = true;
if (label1.Visible == true)
{
button6.Enabled = false;
button4.Enabled = false;
button1.Enabled = false;
}
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("UserId" + "=" + cTextBox2.Text);
w.Close();
timer1.Start();
}
private void button6_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Json Files (*.json)|*.json";
openFileDialog1.FilterIndex = 0;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
cTextBox3.BackColor = Color.White;
cTextBox3.ForeColor = Color.Green;
cTextBox3.Text = openFileDialog1.FileName;
label1.Text = "Updating Settings File";
label1.Visible = true;
if (label1.Visible == true)
{
button6.Enabled = false;
button4.Enabled = false;
button1.Enabled = false;
}
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("JsonFileDirectory" + "=" + cTextBox3.Text);
w.Close();
timer1.Start();
}
}
private void button2_Click(object sender, EventArgs e)
{
ResetValues(true);
}
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
count += 1;
if (count == 2)
{
label1.Visible = false;
timer1.Stop();
count = 0;
}
}
private void Authentication_FormClosing(object sender, FormClosingEventArgs e)
{
ResetValues(false);
}
private void ResetValues(bool DeleteFile)
{
cTextBox1.Text = "";
cTextBox2.Text = "";
cTextBox3.Text = "";
button1.Text = "Confirm";
button4.Text = "Confirm";
button6.Enabled = true;
timer1.Stop();
count = 0;
if (DeleteFile == true)
{
if (File.Exists(AuthenticationFileName))
File.Delete(AuthenticationFileName);
}
Form1.AuthenticationValues.ApiKey = "";
Form1.AuthenticationValues.JsonFileDirectory = "";
Form1.AuthenticationValues.UserId = "";
if (Form1.AuthenticationValues.AuthenticationMenu.Enabled
== false && (Form1.lines.Length < 3 && Form1.lines.Length > 0))
Form1.AuthenticationValues.AuthenticationMenu.Enabled = true;
formclosed = true;
}
}
}
The first problem is in the constructor when checking for the file existing:
if (!File.Exists(AuthenticationFileName))
File.Create(AuthenticationFileName);
This make the file to be busy in use. When later in my code i'm trying to use the file again to write to it i'm getting exception that the file is in use by another process.
The second problem is in the 3 places i'm trying to write to the file.
The first place:
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("Api" + "=" + cTextBox1.Text);
w.Close();
Then under it in another place in the code i'm writing again to the file:
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("UserId" + "=" + cTextBox2.Text);
w.Close();
And last:
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("JsonFileDirectory" + "=" + cTextBox3.Text);
w.Close();
The problems are first the file is busy in use since the checking if exist i'm doing in the constructor.
The second problem is that i want to make that if in the file there is no line that start with "Api" then write the Api part:
w.WriteLine("Api" + "=" + cTextBox1.Text);
But if it does exist and the text is changed in the textBox cTextBox1.Text i want to write to the file the changed text to the place where the Api line is. And to append a new Api line.
Same for all two other places i'm writing to the file.
If i will make it all false not to appen when writing it will write one line each time and will overwrite the line.
But if i'm doing true it will append many Api lines or many UserId lines.
And i want each to time to replace the line with the textBox to overwrite only on this line but with the new text.
If in cTextBox1 there is the text: Hello World
Then i changed it to: Hello World Now
Then replace the Api line Hello World with Hello World Now
Alright, addressing your main concern:
File.CreateFile actually opens a filestream for you to use. Easiest way to solve this is to do File.CreateFile().Close() to close it when you're done.
Next, you are trying to change data in a file, but you never read it to find the information.
You can look up StreamReader and use that, and parse out data and figure out what's where, but there's a much more obvious choice: Just re-write all of the information every time.
I have got the following error message when I trying to create the form object of another form.
any one can help me, What is the solution for this error?
the Training_form which needs to be created as object is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Emgu.CV.UI;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
using System.IO;
using System.Drawing.Imaging;
using System.Xml;
using System.Threading;
namespace Face_Recognition
{
public partial class Training_Form : Form
{
#region Variables
//Camera specific
Capture grabber;
//Images for finding face
Image<Bgr, Byte> currentFrame;
Image<Gray, byte> result = null;
Image<Gray, byte> gray_frame = null;
//Classifier
CascadeClassifier Face;
//For aquiring 10 images in a row
List<Image<Gray, byte>> resultImages = new List<Image<Gray, byte>>();
int results_list_pos = 0;
int num_faces_to_aquire = 10;
bool RECORD = false;
//Saving Jpg
List<Image<Gray, byte>> ImagestoWrite = new List<Image<Gray, byte>>();
EncoderParameters ENC_Parameters = new EncoderParameters(1);
EncoderParameter ENC = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100);
ImageCodecInfo Image_Encoder_JPG;
//Saving XAML Data file
List<string> NamestoWrite = new List<string>();
List<string> NamesforFile = new List<string>();
XmlDocument docu = new XmlDocument();
//Variables
Form1 Parent;
#endregion
public Training_Form(Form1 _Parent)
{
InitializeComponent();
Parent = _Parent;
Face = Parent.Face;
//Face = new HaarCascade(Application.StartupPath + "/Cascades/haarcascade_frontalface_alt2.xml");
ENC_Parameters.Param[0] = ENC;
Image_Encoder_JPG = GetEncoder(ImageFormat.Jpeg);
initialise_capture();
}
private void Training_Form_FormClosing(object sender, FormClosingEventArgs e)
{
stop_capture();
Parent.retrain();
Parent.initialise_capture();
}
//Camera Start Stop
public void initialise_capture()
{
grabber = new Capture();
grabber.QueryFrame();
//Initialize the FrameGraber event
Application.Idle += new EventHandler(FrameGrabber);
}
private void stop_capture()
{
Application.Idle -= new EventHandler(FrameGrabber);
if (grabber != null)
{
grabber.Dispose();
}
//Initialize the FrameGraber event
}
//Process Frame
void FrameGrabber(object sender, EventArgs e)
{
//Get the current frame form capture device
currentFrame = grabber.QueryFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//Convert it to Grayscale
if (currentFrame != null)
{
gray_frame = currentFrame.Convert<Gray, Byte>();
//Face Detector
//MCvAvgComp[][] facesDetected = gray_frame.DetectHaarCascade(Face, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20)); //old method
Rectangle[] facesDetected = Face.DetectMultiScale(gray_frame, 1.2, 10, new Size(50, 50), Size.Empty);
//Action for each element detected
for(int i = 0; i< facesDetected.Length; i++)// (Rectangle face_found in facesDetected)
{
//This will focus in on the face from the haar results its not perfect but it will remove a majoriy
//of the background noise
facesDetected[i].X += (int)(facesDetected[i].Height * 0.15);
facesDetected[i].Y += (int)(facesDetected[i].Width * 0.22);
facesDetected[i].Height -= (int)(facesDetected[i].Height * 0.3);
facesDetected[i].Width -= (int)(facesDetected[i].Width * 0.35);
result = currentFrame.Copy(facesDetected[i]).Convert<Gray, byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
result._EqualizeHist();
face_PICBX.Image = result.ToBitmap();
//draw the face detected in the 0th (gray) channel with blue color
currentFrame.Draw(facesDetected[i], new Bgr(Color.Red), 2);
}
if (RECORD && facesDetected.Length > 0 && resultImages.Count < num_faces_to_aquire)
{
resultImages.Add(result);
count_lbl.Text = "Count: " + resultImages.Count.ToString();
if (resultImages.Count == num_faces_to_aquire)
{
ADD_BTN.Enabled = true;
NEXT_BTN.Visible = true;
PREV_btn.Visible = true;
count_lbl.Visible = false;
Single_btn.Visible = true;
ADD_ALL.Visible = true;
RECORD = false;
Application.Idle -= new EventHandler(FrameGrabber);
}
}
image_PICBX.Image = currentFrame.ToBitmap();
}
}
//Saving The Data
private bool save_training_data(Image face_data)
{
try
{
Random rand = new Random();
bool file_create = true;
string facename = "face_" + NAME_PERSON.Text + "_" + rand.Next().ToString() + ".jpg";
while (file_create)
{
if (!File.Exists(Application.StartupPath + "/TrainedFaces/" + facename))
{
file_create = false;
}
else
{
facename = "face_" + NAME_PERSON.Text + "_" + rand.Next().ToString() + ".jpg";
}
}
if(Directory.Exists(Application.StartupPath + "/TrainedFaces/"))
{
face_data.Save(Application.StartupPath + "/TrainedFaces/" + facename, ImageFormat.Jpeg);
}
else
{
Directory.CreateDirectory(Application.StartupPath + "/TrainedFaces/");
face_data.Save(Application.StartupPath + "/TrainedFaces/" + facename, ImageFormat.Jpeg);
}
if (File.Exists(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml"))
{
//File.AppendAllText(Application.StartupPath + "/TrainedFaces/TrainedLabels.txt", NAME_PERSON.Text + "\n\r");
bool loading = true;
while (loading)
{
try
{
docu.Load(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml");
loading = false;
}
catch
{
docu = null;
docu = new XmlDocument();
Thread.Sleep(10);
}
}
//Get the root element
XmlElement root = docu.DocumentElement;
XmlElement face_D = docu.CreateElement("FACE");
XmlElement name_D = docu.CreateElement("NAME");
XmlElement file_D = docu.CreateElement("FILE");
//Add the values for each nodes
//name.Value = textBoxName.Text;
//age.InnerText = textBoxAge.Text;
//gender.InnerText = textBoxGender.Text;
name_D.InnerText = NAME_PERSON.Text;
file_D.InnerText = facename;
//Construct the Person element
//person.Attributes.Append(name);
face_D.AppendChild(name_D);
face_D.AppendChild(file_D);
//Add the New person element to the end of the root element
root.AppendChild(face_D);
//Save the document
docu.Save(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml");
//XmlElement child_element = docu.CreateElement("FACE");
//docu.AppendChild(child_element);
//docu.Save("TrainedLabels.xml");
}
else
{
FileStream FS_Face = File.OpenWrite(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml");
using (XmlWriter writer = XmlWriter.Create(FS_Face))
{
writer.WriteStartDocument();
writer.WriteStartElement("Faces_For_Training");
writer.WriteStartElement("FACE");
writer.WriteElementString("NAME", NAME_PERSON.Text);
writer.WriteElementString("FILE", facename);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
}
FS_Face.Close();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
//Delete all the old training data by simply deleting the folder
private void Delete_Data_BTN_Click(object sender, EventArgs e)
{
if (Directory.Exists(Application.StartupPath + "/TrainedFaces/"))
{
Directory.Delete(Application.StartupPath + "/TrainedFaces/", true);
Directory.CreateDirectory(Application.StartupPath + "/TrainedFaces/");
}
}
//Add the image to training data
private void ADD_BTN_Click(object sender, EventArgs e)
{
if (resultImages.Count == num_faces_to_aquire)
{
if (!save_training_data(face_PICBX.Image)) MessageBox.Show("Error", "Error in saving file info. Training data not saved", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
stop_capture();
if (!save_training_data(face_PICBX.Image)) MessageBox.Show("Error", "Error in saving file info. Training data not saved", MessageBoxButtons.OK, MessageBoxIcon.Error);
initialise_capture();
}
}
private void Single_btn_Click(object sender, EventArgs e)
{
RECORD = false;
resultImages.Clear();
NEXT_BTN.Visible = false;
PREV_btn.Visible = false;
Application.Idle += new EventHandler(FrameGrabber);
Single_btn.Visible = false;
count_lbl.Text = "Count: 0";
count_lbl.Visible = true;
}
//Get 10 image to train
private void RECORD_BTN_Click(object sender, EventArgs e)
{
if (RECORD)
{
RECORD = false;
}
else
{
if (resultImages.Count == 10)
{
resultImages.Clear();
Application.Idle += new EventHandler(FrameGrabber);
}
RECORD = true;
ADD_BTN.Enabled = false;
}
}
private void NEXT_BTN_Click(object sender, EventArgs e)
{
if (results_list_pos < resultImages.Count - 1)
{
face_PICBX.Image = resultImages[results_list_pos].ToBitmap();
results_list_pos++;
PREV_btn.Enabled = true;
}
else
{
NEXT_BTN.Enabled = false;
}
}
private void PREV_btn_Click(object sender, EventArgs e)
{
if (results_list_pos > 0)
{
results_list_pos--;
face_PICBX.Image = resultImages[results_list_pos].ToBitmap();
NEXT_BTN.Enabled = true;
}
else
{
PREV_btn.Enabled = false;
}
}
private void ADD_ALL_Click(object sender, EventArgs e)
{
for(int i = 0; i<resultImages.Count;i++)
{
face_PICBX.Image = resultImages[i].ToBitmap();
if (!save_training_data(face_PICBX.Image)) MessageBox.Show("Error", "Error in saving file info. Training data not saved", MessageBoxButtons.OK, MessageBoxIcon.Error);
Thread.Sleep(100);
}
ADD_ALL.Visible = false;
//restart single face detection
Single_btn_Click(null, null);
}
private void Training_Form_Load(object sender, EventArgs e)
{
}
}
}
the form which needs to create the object of Training_Form is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Runtime.InteropServices;
using System.Threading;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace Face_Recognition
{
public partial class mainwindow : Form
{
public mainwindow()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Form1 childf = new Form1();
childf.ShowDialog();
}
private void mainwindow_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
Training_Form TF = new Training_Form(this);
TF.Show();
}
}
}
It seems that this does not refer to an instance of Form1 but a different Form-type Face_Recognition. But the constructor of Training_Form only accepts Form1 as parameter. So you either have to pass an instance of Form1 if you have one or change the signature of the constructor.
Maybe it's sufficient to use a Form:
public Training_Form(Form _Parent)
{
InitializeComponent();
Parent = _Parent;
Face = Parent.Face;
//Face = new HaarCascade(Application.StartupPath + "/Cascades/haarcascade_frontalface_alt2.xml");
ENC_Parameters.Param[0] = ENC;
Image_Encoder_JPG = GetEncoder(ImageFormat.Jpeg);
initialise_capture();
}
If you need the Form1 you have to pass an instance. You are creating one in button2_Click but just as local variable. You could store it in a field:
Form1 childf = null;
private void button2_Click(object sender, EventArgs e)
{
if(childf == null) childf = new Form1();
childf.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
if(childf == null) childf = new Form1();
Training_Form TF = new Training_Form(childf);
TF.Show();
}
Your Training_Form expects a parameter of type Form1.
While in your code you are trying to supply it with the keyword this. this being the object you are currently in. Since you are calling it from mainwindow you are trying to put a mainwindow type in it, because in this case mainwindow is equal to this.
You probably, by reading your code, mean to put the childf in, or at least, that has the right type.
That would work, but you would have to declare the childf parameter more globally.
Or you should change the type you expect in your constructor to mainwindow that would work as well.
You are sending training form an argument of "this" from your program which is a reference to program so you are getting an invalid argument. You either need to make the call to display the TrainingForm from within Form1 or make Form1 a private instantiated member of the program so you can pass it into the TrainingForm constructor.
I am coding a program where I need to read, write, and filter data from one text file to a new one.
The main goal of this program is:
have the user select a text file with data that I have already created,
use a Substring to choose which characters to grab from the file,
write a file that matches the data from the text file.
I am a little stuck on getting the program to write files in general as well as grabbing certain characters from a text file.
If anyone could give me some pointers that would be awesome.
Thanks!
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.Diagnostics;
using System.IO;
namespace Project_4_osmvoe
{
public partial class Form1 : Form
{
string ham;
StreamReader pizza;
StreamWriter burger;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
ham = openFileDialog1.FileName;
}
pizza = new StreamReader(ham);
lblInputFile.Text = ham;
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
ham = saveFileDialog1.FileName;
}
burger = new StreamWriter(ham);
lblOutputFile.Text = ham;
}
private void button3_Click(object sender, EventArgs e)
{
string line;
while ((line = pizza.ReadLine()) != null)
{
if (filter(line))
burger.WriteLine(line);
}
pizza.Close();
burger.Close();
MessageBox.Show("Output File Written");
}
private Boolean filter(string intext)
{
string gender = intext.Substring(0, 0);
string state = intext.Substring(0, 0);
if (((radioButtonFemale.Checked && gender.Equals("F")) ||
(RadioButtonMale.Checked && gender.Equals("M"))))
return true;
else
return false;
}
}
}
A part from the useful advices received in the comments above.
(Don't keep streams opened between events)
What do you think is the result of these lines?
string gender = intext.Substring(0, 0);
string state = intext.Substring(0, 0);
THe second parameter of Substring is the number of chars to extract from the string. Passing zero means that your returned string is empty, so the subsequent test is always false and you never write a line.
I suggest to store, in two different global variables, the names of the two files and, in button3_Click open the two streams
string inputFile;
string outputFile;
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
inputFile = openFileDialog1.FileName;
lblInputFile.Text = inputFile;
}
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
outputFile = saveFileDialog1.FileName;
lblOutputFile.Text = outputFile ;
}
}
private void button3_Click(object sender, EventArgs e)
{
string line;
using(StreamReader pizza = new StreamReader(inputFile))
using(StreamWriter burger = new StreamWrite(outputFile))
{
while ((line = pizza.ReadLine()) != null)
{
if (!string.IsNullOrWhiteSpace(line) && filter(line))
burger.WriteLine(line);
}
}
MessageBox.Show("Output File Written");
}
private Boolean filter(string intext)
{
string gender = intext.Substring(0, 1);
string state = intext.Substring(0, 1);
if (((radioButtonFemale.Checked && gender.Equals("F")) ||
(RadioButtonMale.Checked && gender.Equals("M"))))
return true;
else
return false;
}