Okay so yes I am doing homework and I am SO close on this one I know it, but ive been messing with it for over an hour and now I'm going insane, if i take the loop out my program will read the file and say weather you passed but it wont write the wrong answers in the listbox, if i put in my foreach code it gives me a syntax error.
this is my current 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;
namespace DriversLicenseExam
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] answerArray ={"B","D","A","A","C",
"A", "B","A","C","D",
"B", "C","D","A","D",
"C", "C","B","D","A"};
string[] studentansArray = new string[20];
List<string> incorrectList = new List<string>();
int count = 0, index = 0, qnumber = 0;
try
{
string filename = "../../" + filenametxt.Text;
StreamReader inputFile = File.OpenText(filename);
while(!inputFile.EndOfStream)
{
studentansArray[index] = inputFile.ReadLine();
if (studentansArray[index] == answerArray[index])
count++;
else
{
qnumber = index + 1;
incorrectList.Add(qnumber.ToString());
}
index++;
}
inputFile.Close();
if (count >= 15)
{
resultoutput.Text = "You Passed The Test!";
}
else
resultoutput.Text = "You Failed The Test... You're a Failure!";
}
foreach (string str in incorrectList) // <<-- error is here
{
lbox.Items.Add(str);
} // <<-- error is here
catch (Exception)
{
MessageBox.Show("File Not Found");
}
}
private void button2_Click(object sender, EventArgs e)
{
filenametxt.Text = "";
resultoutput.Text = "";
lbox.Items.Clear();
}
private void exitbutton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I'm not 100% sure about this, but your foreach is between your try and catch block, maybe try with that:
try
{
string filename = "../../" + filenametxt.Text;
StreamReader inputFile = File.OpenText(filename);
while(!inputFile.EndOfStream)
{
studentansArray[index] = inputFile.ReadLine();
if (studentansArray[index] == answerArray[index])
count++;
else
{
qnumber = index + 1;
incorrectList.Add(qnumber.ToString());
}
index++;
}
inputFile.Close();
if (count >= 15)
{
resultoutput.Text = "You Passed The Test!";
}
else
resultoutput.Text = "You Failed The Test... You're a Failure!";
foreach (string str in incorrectList)
{
lbox.Items.Add(str);
}
}
catch (Exception)
{
MessageBox.Show("File Not Found");
}
Related
Hey I want to create a windows application that should display the total lines, Blank lines and commented lines. I am able to calculate Total Lines, Can any one help me with the logic for blank lines and commented lines!
I want to count the Lines Of Code, for any file, i.e .html, .css, .cs, etc.
Also if possible I want the result to be exported to a Excel File!
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 Line_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
textbox1.Clear();
textbox2.Clear();
if (ofd.ShowDialog() == DialogResult.OK)
{
string strFilename = ofd.FileName;
textbox1.Text = Path.GetFileName(strFilename);
StreamReader sr = File.OpenText(strFilename);
int nLineCount = 0;
while (sr.ReadLine() != null)
{
nLineCount++;
}
textbox1.Text = nLineCount.ToString("0,0");
sr.Close();
}
}
private void txtFileName_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I want more text boxes that should display count of blank lines, Commented lines, and finally the total count (i.e. subtracting the no. of blank lines and commented lines from total no of lines)
If Possible single button_click for each or all in one.enter image description here
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 LOC_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void getFileList(string directory)
{
string[] dirs = Directory.GetDirectories(directory);
foreach (string dir in dirs)
{
getFileList(dir);
}
string[] files = Directory.GetFiles(directory);
foreach (string file in files)
{
StreamReader sr = File.OpenText(file);
int nLineCount = 0;
string str = string.Empty;
while (!sr.EndOfStream)
{
str = sr.ReadLine();
if (str != null && str.Length > 0 && (str.Length > 2 && str.Substring(0, 2) != "//") && (str.Length > 3 && str.Substring(0, 4) != "<!--"))
nLineCount++;
}
lstbxResult.Items.Add(file + " Line count - " + nLineCount);
}
}
private void btnBrowse_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog() == DialogResult.OK)
{
lstbxResult.Items.Clear();
getFileList(FBD.SelectedPath);
}
}
public static void ExportToExcel(ListBox lst, string excel_file)
{
int cols;
//open file
StreamWriter wr = new StreamWriter(excel_file);
//write rows to excel file
for (int i = 0; i < (lst.Items.Count - 1); i++)
{
wr.Write(lst.Items[i].ToString() + "\t");
wr.WriteLine();
}
//close file
wr.Close();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I'm doing project in C# that read from a video file and convert it to subtitle text, but i want to get the start time for each text line so it can be shown in the video at the right time, i tried the AudioPosition but it not working well, is there a away to do this?
using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Threading.Tasks;
namespace project
{
public partial class Form1 : Form
{
StringBuilder sb = new StringBuilder();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
string[] tokens;
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "WAV|*.wav";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
SpeechRecognitionEngine sre = new SpeechRecognitionEngine();
Grammar gr = new DictationGrammar();
sre.LoadGrammar(gr);
sre.SetInputToWaveFile(#openFileDialog1.FileName);
while (true)
{
try
{
var recText = sre.Recognize();
sb.Append(recText.Audio.AudioPosition + " * ");
textBox4.Text = sb.ToString();
tokens = sb.ToString().Split('#');
for (int i = 0; i < tokens.Length - 1; i++)
{
textBox2.AppendText(tokens.Length.ToString());
textBox2.AppendText(i+" - "+tokens[i]);
textBox2.AppendText(Environment.NewLine);
}
}
catch (Exception ex)
{
break;
}
}
}
I'm trying to create an antivirus program that takes a group of 5 MD 5 hashes from a text file and after the user select a folder using browse and clicks scan the program should iterate through all the files run the hash for each one in a background worker and compare, if the result is a virus detected, the result is then fed to a list box.
Currently the code is catching (FileNotFoundException) and the msgbox displaying FilePath is producing "Path1" "Path2" "Path3", could anyone explain how i can correct the code so that the paths are being correctly fed? I don't really understand where the "Path1" "Path2" "Path3" ect is coming from?
Code Below :
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.Text.RegularExpressions;
using System.Security.Cryptography;
namespace TestAntivirus
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int noofvirus = 0;
List<string> completehashes = new List<string>();
private void Browse_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
label1.Text = folderBrowserDialog1.SelectedPath;
noofvirus = 0;
label2.Text = "Viruses:" + noofvirus.ToString();
progressBar1.Value = 0;
listBox1.Items.Clear();
}
private void BDone_Click(object sender, EventArgs e)
{
this.Close();
}
private void BScan_Click(object sender, EventArgs e)
{
string[] scanned = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
int numofscanned = scanned.Count();
progressBar1.Maximum = scanned.Length;
foreach (string item in scanned)
{
for (int i = 0; i < (numofscanned); i++)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler (backgroundWorker1_DoWork);
worker.RunWorkerAsync(i);
}
}
foreach (string hashes in completehashes)
{
try
{
StreamReader stream = new StreamReader(hashes);
string read = stream.ReadToEnd();
var lineCount = File.ReadLines(#"C:\Users\Neil Bagley\Desktop\ProjectWork\VirusHashes\Test5.txt").Count();
var virus = File.ReadAllLines(#"C:\Users\Neil Bagley\Desktop\ProjectWork\VirusHashes\Test5.txt");
foreach (string st in virus)
{
if (Regex.IsMatch(read, st))
{
MessageBox.Show("Virus Detected");
noofvirus += 1;
label2.Text = "Viruses: " + noofvirus.ToString();
listBox1.Items.Add(hashes);
}
progressBar1.Increment(1);
}
}
catch
{
string read = hashes;
var virus = File.ReadAllLines(#"C:\Users\Neil Bagley\Desktop\ProjectWork\VirusHashes\Test5.txt");
foreach (string st in virus)
{
if (Regex.IsMatch(read, st))
{
MessageBox.Show("Virus Detected");
noofvirus += 1;
label2.Text = "Viruses:" + noofvirus.ToString();
listBox1.Items.Add(hashes);
}
}
}
}
}
private static String MakeHashString(byte[] hashbytes)
{
StringBuilder hash = new StringBuilder(32);
foreach (byte b in hashbytes)
{
hash.Append(b.ToString("X2").ToLower());
}
return hash.ToString();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string filePath = e.Argument.ToString();
byte[] buffer;
int bytesRead;
long size;
long totalBytesRead = 0;
try
{
using (Stream file = File.OpenRead(filePath))
{
size = file.Length;
using (HashAlgorithm hasher = MD5.Create())
{
do
{
buffer = new byte[4096];
bytesRead = file.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
hasher.TransformBlock(buffer, 0, bytesRead, null, 0);
backgroundWorker1.ReportProgress((int)((double)totalBytesRead / size * 100));
} while (bytesRead != 0);
hasher.TransformFinalBlock(buffer, 0, 0);
e.Result = MakeHashString(hasher.Hash);
}
}
}
catch (FileNotFoundException)
{
MessageBox.Show("File not found in the specified path" + filePath);
}
catch (IOException)
{
MessageBox.Show("IOException");
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
completehashes.Add(e.Result.ToString());
progressBar1.Value = 0;
}
}
}
After the advice previously given i have tried to start remaking the project, but im now unsure why this only adds one hash to the listbox rather all as i expected with "foreach (string scan in scanned)" can anyone explain?
New Attempt:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
namespace AntiVirus
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int noofvirus = 0;
private string[] scanned;
private void BBrowse_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
label1.Text = folderBrowserDialog1.SelectedPath;
noofvirus = 0;
label2.Text = "Viruses:" + noofvirus.ToString();
progressBar1.Value = 0;
listBox1.Items.Clear();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
scanned = Directory.GetFiles(e.Argument.ToString(), "*.*", SearchOption.AllDirectories);
foreach (string scan in scanned)
{
byte[] buffer;
int bytesRead;
long size;
long totalBytesRead = 0;
using (Stream file = File.OpenRead(scan))
{
size = file.Length;
using (HashAlgorithm hasher = MD5.Create())
{
do
{
buffer = new byte[4096];
bytesRead = file.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
hasher.TransformBlock(buffer, 0, bytesRead, null, 0);
backgroundWorker1.ReportProgress((int)((double)totalBytesRead / size * 100));
} while (bytesRead != 0);
hasher.TransformFinalBlock(buffer, 0, 0);
e.Result = MakeHashString(hasher.Hash);
}
}
}
}
private static String MakeHashString(byte[] hashbytes)
{
StringBuilder hash = new StringBuilder(32);
foreach (byte b in hashbytes)
{
hash.Append(b.ToString("X2").ToLower());
}
return hash.ToString();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
listBox1.Items.Add(e.Result.ToString());
progressBar1.Value = 0;
}
private void BScan_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync(folderBrowserDialog1.SelectedPath);
}
private void BDone_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
You set e.Result for each hash, but only when the RunWorkerCompleted event is fired does it get added to the listbox.
(that event only fires once when the DoWork Event has completed, so only the last hash gets added)
I would recommand using backgroundWorker1.ReportProgress 2nd parameter userState when you've got the file hash like so:
(note, code is untested/psuedocode but it hopefully gets you on the right track)
//CalculateTotalProgress() is a fictional function returning total progress percentage
backgroundWorker1.ReportProgress(CalculateTotalProgress(currentFile,totalFiles), MakeHashString(hasher.Hash));
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
listBox1.Items.Add(e.UserState.ToString);
progressBar1.Value = e.ProgressPercentage;
}
All of a sudden my form window has begun to close as soon as the application is launched. There's nothing in the output window that gives a hint as to what could be causing it and there are no errors thrown at me either. Does anybody have any ideas?
I've provided to form's class.
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;
namespace ProjectBoardManagement {
public partial class CreateBoard : Form {
Functions funcs = new Functions();
public CreateBoard() {
InitializeComponent();
}
private void CreateBoardButton_Click(object sender, EventArgs e) {
String BoardName = BoardNameText.Text;
String Pages = "";
String Labels = "";
foreach (ListViewItem i in PageNameList.Items) {
Pages = (Pages + i.Name.ToString() + ",");
}
foreach (ListViewItem i in LabelNameList.Items) {
Labels = (Labels + i.Name.ToString() + ",");
}
String BoardFile = ("board_" + BoardName + ".txt");
funcs.SaveSetting(BoardFile, "name", BoardName);
funcs.SaveSetting(BoardFile, "pages", Pages);
funcs.SaveSetting(BoardFile, "labels", Labels);
FormManagement.CreateBoard.Hide();
FormManagement.BoardList.LoadBoardList();
}
private void PageNameButtonAdd_Click(object sender, EventArgs e) {
String pagename = PageNameText.Text;
if (pagename != "") {
PageNameList.Items.Add(pagename);
}
PageNameText.Text = "";
}
private void LabelNameButtonAdd_Click(object sender, EventArgs e) {
String labelname = LabelNameText.Text;
if (labelname != "") {
LabelNameList.Items.Add(labelname);
}
LabelNameText.Text = "";
}
}
}
Obvious first thing to do - run it in Debug mode and stop execution on all exceptions. This should give you enough information on how to go from there.
Otherwise Functions funcs = new Functions(); looks suspicious.
This is my xml file;
<UserClass>
<Id>1</Id>
<Name>oss</Name>
<Address>
<Id>1</Id>
<Street>asstreet</Street>
</Address>
</UserClass>
So I want to add these "nodes" to comboBox items.
When user typed UserClass and type "."(dot) to end of "UserClass"; Id, Name and other things have to listed in combobox.
User typed "UserClass." and -> combobox get these;
UserClass.Id
UserClass.Name
UserClass.Address.Id
UserClass.Address.Street
I tried many things, include that one;
...
try
{
string parsedNode = ParseComboBox();
XmlReader rdr = XmlReader.Create(new System.IO.StringReader(_globalXml));
comboBox1.Items.Clear();
while (rdr.Read())
{
if (rdr.NodeType == XmlNodeType.Element)
{
comboBox1.Items.Add(rdr.LocalName);
}
comboBox1.DroppedDown = true;
}
//string parsedNode = ParseComboBox();
//XmlNodeList childList = xml.GetElementsByTagName(parsedNode);
////comboBox1.Items.Clear();
//foreach (XmlNode node in childList)
//{
// foreach (var osman in node.ChildNodes)
// {
// comboBox1.Items.Add(parsedNode + "." + osman);
// }
//}
}
catch (Exception)
{
MessageBox.Show("fuuu");
}
}...
private string ParseComboBox()
{
string resultAsXmlNodes = null;
string text = comboBox1.Text;
if (text.EndsWith("."))
{
char[] delimiterChars = { '.' };
string[] words = text.Split(delimiterChars);
foreach (string s in words)
{
resultAsXmlNodes += s;
}
}
return resultAsXmlNodes;
}
It's not working correctly. I believe there is an easy way to do it.
So, what is the simple way? Or simply,
How can I show node names in comboBox ?
I found multiple problems with this. Here's some example code that I got working for a form project with an XML File and one ComboBox control:
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;
using System.Xml;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.KeyDown += comboBox1_KeyDown;
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Decimal:
case Keys.OemPeriod:
LoadComboItems(comboBox1.Text);
break;
default:
break;
}
}
void LoadComboItems(string userInput)
{
comboBox1.Items.Clear();
string lookupName = userInput.Trim();
if (lookupName.Length > 0)
{
string _globalXML = Application.StartupPath + #"\XMLFile1.xml";
XmlReader rdr = XmlReader.Create(_globalXML);
while (rdr.Read())
{
if (rdr.LocalName == lookupName)
{
string ElementName = "";
int eCount = 0;
int prevDepth = 0;
while (rdr.Read())
{
if (rdr.NodeType == XmlNodeType.Element)
{
ElementName += '.' + rdr.LocalName;
eCount++;
}
else if (rdr.NodeType == XmlNodeType.EndElement && eCount == rdr.Depth)
{
if (rdr.Depth >= prevDepth)
{
comboBox1.Items.Add(lookupName + ElementName);
int pos = ElementName.LastIndexOf('.');
ElementName = ElementName.Substring(0, pos);
prevDepth = rdr.Depth;
}
eCount--;
}
}
}
}
if (rdr != null)
{
rdr.Close();
}
comboBox1.DroppedDown = true;
}
}
}
}