Winforms - Listbox will not update contenets until clicked - c#

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;
}
}
}
}

Related

Save File to .txt after finishing operation

I already got most of the help I needed in order to create a working button to save my scraped proxies to a .txt file, but I still run into one issue. This is the code that I have gotten so far, it works perfectly fine:
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Windows.Forms;
using System.IO;
namespace CyberScraper
{
public partial class Base_Scraper : Form
{
WebClient _WC = new WebClient();
Defaults _DF = new Defaults();
public Base_Scraper()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
}
private void Base_Scraper_Load(object sender, EventArgs e)
{
MessageBox.Show("twitch.tv/CyberLost same YT Name");
}
private void ScrapeTheProxies()
{
try
{
foreach (string Source in ScrapeSources.Lines)
{
string UnparsedWebSource = _WC.DownloadString(Source);
MatchCollection _MC = _DF.REGEX.Matches(UnparsedWebSource);
foreach (Match Proxy in _MC)
{
GatheredProxies.Items.Add(Proxy);
}
}
}
catch (Exception)
{
}
}
private void SaveProxyResults_Click(object sender, System.EventArgs e)
{
Stream myStream;
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "";
dlg.InitialDirectory = #"C:\Users\username\Desktop";
dlg.Filter = "txt files (*.txt)|*.txt";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == DialogResult.OK)
{
if ((myStream = dlg.OpenFile()) != null)
{
myStream.Close();
StreamWriter writer = new StreamWriter(dlg.FileName);
for (int i = 0; i < GatheredProxies.Items.Count; i++)
{
writer.WriteLine((string)GatheredProxies.Items[i]);
}
writer.Close();
}
}
dlg.Dispose();
}
private void BackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
ScrapeTheProxies();
}
private void ScrapeButton_Click(object sender, EventArgs e)
{
BackgroundWorker.RunWorkerAsync();
}
}
}
When I click on "Save Results" it works before I scraped the proxies, if I do it after finishing scraping the proxies it outputs this error and saves it on the desktop as an empty .txt file instead of a .txt file containing the scraped proxies:
System.InvalidCastException: 'Unable to cast object of type 'System.Text.RegularExpressions.Match' to type 'System.String'.'
in:
writer.WriteLine((string)GatheredProxies.Items[i]);

The directory is invalid. What is going wrong? copying file from source to destination

So I am trying to copy a file from a source to a destination. I'm creating a windows form where i have buttons, source and destination. They are used to get a file and then get a desination. then another button is used to copy that file to the destination. when i click the destination, I get 'The directory name is invalid'.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CopyDirectory
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
string file = "";
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
//opens the file source & shows it in a label
file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
int size = text.Length;
string sfile = Path.GetFileName(file);
lbl_sfile.Text = sfile; // for full location
}
catch (IOException)
{
}
}
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
//saves the file destination & shows it in a label
//use file2 string to save file into destination
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
lbl_dfile.Text = folderBrowserDialog1.SelectedPath;
}
}
}
private void Caluculate(int i)
{
double pow = Math.Pow(i, i);
}
private void bttn_savefile_Click(object sender, EventArgs e)
{
//collect label text as strings
string file2 = lbl_sfile.Text.ToString();
string file3 = lbl_dfile.Text.ToString();
string sourceDir = file;
string backupDir = folderBrowserDialog1.SelectedPath;
Path.Combine(file2, Path.GetFileName(file3));
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
// Set the initial value of the ProgressBar.
progressBar1.Value = 10;
progressBar1.Maximum = 100000;
progressBar1.Step = 1;
for (int j = 0; j < 100000; j++)
{
Caluculate(j);
progressBar1.PerformStep();
}
}
private void progressBar1_Click(object sender, EventArgs e)
{
}
}
}
First of all, for some clean code, your field named file should at least be a property and the name should reflect what it actually is, so:
string file = "";
to
private string FileFullPath { get; set; }
Then the real problem is that you are assigning the full path of the file, including its name to file: file = openFileDialog1.FileName; but then treating it as a directory string sourceDir = file; that should be obvious as to why that would fail... if not... you need to take the full path and just get the directory ie:
var sourceDir = Path.GetDirectoryName(FileFullPath);

App Can't add tables to Sql server Database

I have written a news web application. I think code is right but it return false when the function Add news is called
/*my form
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using WindowsFormsApp1.Models;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
byte[] picture = null;
WebClient ObjWebClient = null;
List<CategoriesGET>ListCategories = null;
public Form1()
{
InitializeComponent();
//---------------------------------
ObjWebClient = new WebClient();
ObjWebClient.Headers[HttpRequestHeader.ContentType]= "application/json ; charset=utf-8";
string url = "http://localhost:3712/api/CategoriesApi/GetCategories";
string JsonResponse = ObjWebClient.DownloadString(url);
ListCategories = JsonConvert.DeserializeObject<List<CategoriesGET>>(JsonResponse);
cmb_NewsCategories.DataSource = ListCategories.Select(q=>q.CategoryTitle).ToList();
}
private void RefreshForms()
{
Txt_NewsTitle.Text = string.Empty;
Txt_NewsDescription.Text = string.Empty;
Txt_NewsDescription.Text = "لطفا دسته خبر را انتخاب کنید";
NewsImage.Image = Properties.Resources._2;
}
private void button3_Click(object sender, EventArgs e)
{
string url = "http://localhost:3712/api/NewsApi/AddNews/?NewsJson=";
ObjWebClient = new WebClient();
ObjWebClient.Headers[HttpRequestHeader.ContentType] = "application/json ; charset=utf-8";
ObjWebClient.Encoding = UTF8Encoding.UTF8;
//-------------------------------
PostNewsModel ObjPost = new PostNewsModel();
ObjPost.NewsTitle = Txt_NewsTitle.Text;
ObjPost.NewsDescription = Txt_NewsDescription.Text;
ObjPost.FK_CategoryID = ListCategories[cmb_NewsCategories.SelectedIndex].CategoryID;
ObjPost.NewsPicture = picture;
//-------------------------------------------------
string JsonData = JsonConvert.SerializeObject(ObjPost);
string Response = ObjWebClient.UploadString(url, JsonData);
MessageBox.Show(Response);
}
private void button4_Click(object sender, EventArgs e)
{
OpenFileDialog OFD = null;
string ImgPath = null;
OFD = new OpenFileDialog();
OFD.Title = "انتخاب عکس";
OFD.Filter = "JpegFiles|*.jpg";
if (OFD.ShowDialog() == DialogResult.OK)
{
if(OFD.FileName != null)
{
ImgPath = OFD.FileName;
NewsImage.Image = System.Drawing.Image.FromFile(ImgPath);
picture = AppClasses.Utility.ConvertImageToByte(NewsImage.Image, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
private void Txt_NewsTitle_TextChanged(object sender, EventArgs e)
{
}
}
}
//Add news function
public bool AddNews([FromBody]TB_News_Post NewsJson)
{
bool Succesfull =false;
try
{
string ImageLabel = GeneratePicName();
string Picture = ByteToImage(NewsJson.NewsPicture, ImageLabel);
TB_News Tbl_News = new TB_News();
Tbl_News.FK_CategoryID = NewsJson.FK_CategoryID;
Tbl_News.NewsDescription = NewsJson.NewsDescription;
Tbl_News.NewsPicture = Picture;
Tbl_News.NewsTitle = NewsJson.NewsTitle;
Tbl_News.NewsDate = DateTime.Now;
DbContext.TB_News.Add(Tbl_News);
DbContext.SaveChanges();
Succesfull = true;
}
catch (Exception)
{
Succesfull = false;
}
return Succesfull;
please help and feel free to ask the whole project thnx a lot

Getting,reading,writing, and saving into one .txt file a collection of .txt documents contents. in visual c# using windows form

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

Reading and writing text files in C#

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;
}

Categories

Resources