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();
}
}
}
Related
The goal of this project in C# is to browse for a txt file in each box (that coding works) and hit submit and each side will run to select the top ten repeated words in each listbox. I have got most of the code to work but I can only get book 1 side to run and not book 2. Attached is the code as well as the image to help understand! Using Windows Desktop (.NET) application.
using System;
using System.Collections;
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 Asynchronous_Program
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e) => Close();
private async void btnSubmit_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
listBox2.Items.Clear();
List<Task> tasks = new List<Task>();
var file = openFileDialog1.FileName;
var wordTask = ReadBook(file);
tasks.Add(wordTask);
await Task.WhenAll(tasks);
//Other operations after this has finished
}
private async Task ReadBook(string filename)
{
var lines = await Task.FromResult(File.ReadAllLinesAsync(filename));
var arrayLinesWithoutPunctuation =
lines.Result.Where(x => x != String.Empty)
.AsParallel()
.Select(x => x.ToLower().Trim().Replace(",", "").Replace("{", ""));
var arrayOfWords = arrayLinesWithoutPunctuation.SelectMany(x => x.Split(" "));
Dictionary<string, int> wordDic = new Dictionary<string, int>();
arrayOfWords.ToList().ForEach(x =>
{
if (wordDic.ContainsKey(x))
{
wordDic[x] += 1;
}
else
{
wordDic.Add(x, 1);
}
});
var top10 = wordDic.Where(x =>
!string.IsNullOrWhiteSpace(x.Key)).OrderByDescending(x => x.Value).Take(10);
foreach(var word in top10)
{
listBox1.Items.Add(word.Key + " - " + word.Value);
listBox2.Items.Add(word.Key + " - " + word.Value);
}
}
private void btnBrowse_Click(object sender, EventArgs e)
{
DialogResult result = this.openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
txtFileName.Text = openFileDialog1.FileName.Split("\\").LastOrDefault();
}
}
private void btnBrowse2_Click(object sender, EventArgs e)
{
DialogResult result = this.openFileDialog2.ShowDialog();
if (result == DialogResult.OK)
{
txtFileName2.Text = openFileDialog2.FileName.Split("\\").LastOrDefault();
}
}
}
}
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");
}
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;
}
}
}
This is my first question in Stackoverflow
I am trying to convert some files(.txt,.mp3,.mp4,.pdf,.png,.exe etc.) in a folder to a format .rjb, created by me. And I also want to recover the original files from the .rjb files. But every files other than .txt files get corrupted. Please help me, to accomplish this. The below code is what I am using.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace rjbformat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
try
{
//string data = Convert.ToString(File.ReadAllBytes(textBox1.Text));
// string datas = File.ReadAllText(textBox1.Text);
//string dat = File.ReadAllText(textBox1.Text, Encoding.ASCII);
//var dataS = Convert.ToString(datas);
using (StreamWriter sw = new StreamWriter(textBox1.Text + ".rjb"))
{
sw.Write(textBox3.Text);
}
}
catch (Exception)
{
MessageBox.Show("Specified Input file DOESNOT EXIST!", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
//throw;
}
}
else
{
MessageBox.Show("Please select Input file");
}
}
private void button2_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Open Text File (Rajib)";
openFileDialog1.Filter = "Text Files(*.txt;*.cod;*.ubc)|*.txt;*.cod;*.ubc";
openFileDialog1.Filter = "All Files(*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
textBox2.Text = openFileDialog1.FileName + ".rjb";
File.Copy(textBox1.Text, textBox2.Text,true);
FileAccess.ReadWrite.ToString(textBox1.Text);
var lines = File.ReadAllLines(textBox1.Text);
/* foreach (string line in lines)
{
textBox3.Text += line+"\r\n";
}*/
File.AppendAllLines(textBox2.Text, lines);
// FileStream fs = new FileStream(textBox1.Text, FileMode.Open);
// int hexIn;
// String hex = "";
// for (int i = 0; i<50/*(hexIn = fs.ReadByte()) != -1*/; i++)
// {
// hex = string.Format("{0:X2}", fs.ReadByte());
// // int bina = fs.ReadByte();
// textBox3.Text += hex;
//}
}
}
}
}
If all you are doing is storing one or more files into your .rjb format and want to get them back intact, this sounds a lot like creating archive files. In that case, you may want to consider just using a standard zip file and customize the extension.
Here's an example using the ZipArchive class:
using System.IO.Compression;
namespace CustomZip
{
class Program
{
static void Main(string[] args)
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.rjb";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
You will need to add a reference to System.IO.Compression.FileSystem to your project.
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.