c# Split Strings Into Separate Text Boxes [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am a beginner. I have code to read in a text file, and part of how to get the strings into a text box. The format of the text file is like DREC: 04HF; and then the next begins with that same format. I need to read that from the text file and split it into 2 separate text boxes (3,4) at a : or a ; . Thank you for the help.
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 WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
textBox1.Text = of.FileName;
}
private void button2_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(textBox1.Text);
textBox2.Text = sr.ReadToEnd();
sr.Close();
}
private void button3_Click(object sender, EventArgs e)
{
int lcount;
string s;
int i;
lcount = textBox2.Lines.Length;
s = textBox2.Lines[0];
for (i = 0; i < lcount; i++)
{
textBox4.Text = textBox2.Lines[i];
}
textBox4.Text = s;
}
}

I need a better description of what you are doing but maybe this will help
//split apart segments
string[] split1 = textBox2.Text.Split(';');
foreach (string segment in split1)
{
//split sub-segment
string[] split2 = segment.Split(':');
//check if it's valid
if (split2.Count().Equals(2))
{
textBox3.Text += String.Format("{0}{1}", split2[0].Trim(), Environment.NewLine);
textBox4.Text += String.Format("{0}{1}", split2[1].Trim(), Environment.NewLine);
}
else
{
throw new ArgumentException("Invalid Segment");
}
}

Related

C# Windows Application LOC_Counter

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

How to use C# to convert any file to some other arbitrary format(.rjb) & recover to original format?

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.

c# find and replace an unknown word between markers/know words

Im trying to make a program that replace a word in a file but i dont know how to replace when the word is now a unknown word
this is my code for replace when the file is unmodified, but when the user change the word/nickname and want to change it again, i need to know that word/nickname between 2 words
string path2 = filePath + "\\test\\versions\\"+comboBox1.Text+"\\";
string text = File.ReadAllText(path2+comboBox1.Text+".json");
text = text.Replace("${auth_player_name}", textBox1.Text);
File.WriteAllText(path2+comboBox1.Text+".json", text);
this is the 2 words between the word that i need to replace
--username ${auth_player_name} --version
now im trying to change the unknown word to ${auth_player_name} so the user can change it again, this need to be that word because my program can edit other files that are similar but with other name
i tried this but dont work
text = Regex.Replace(text, "--username \".*\" --ver", "-username \"${auth_player_name}\" --ver");
This is all the code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
namespace ChangeName
{
public partial class Form1 : Form
{
string filePath = Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
public Form1()
{
InitializeComponent();
DirectoryInfo dinfo = new DirectoryInfo(filePath+"\\.minecraft\\versions");
FileInfo[] Files = dinfo.GetFiles("*.json", SearchOption.AllDirectories);
foreach (FileInfo folder in Files)
comboBox1.Items.Add(Path.GetFileNameWithoutExtension(folder.Name));
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string path2 = filePath + "\\.minecraft\\versions\\"+comboBox1.Text+"\\";
string text = File.ReadAllText(path2+comboBox1.Text+".json");
text = text.Replace("${auth_player_name}", textBox1.Text);
File.WriteAllText(path2+comboBox1.Text+".json", text);
}
}
}
Regex.Replace Example
string path2 = filePath + "\\test\\versions\\"+comboBox1.Text+"\\";
string text = File.ReadAllText(path2+comboBox1.Text+".json");
//Changed to Regex
Regex reg = new Regex("--username ([^-]+)--version");
//using regex.replace function
text = reg.Replace(text, "--username " + textBox1.Text + " --version");
//end edit
File.WriteAllText(path2+comboBox1.Text+".json", text);
Documentation for Regex.Replace
Updated to set text variable equal to the replacement.

How to resize multiple images [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
My task is to resize multiple images. I tried this 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 Boyutlandir
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string dosyaYolu = string.Empty;
Bitmap bmp = null;
OpenFileDialog openFileDialogDosyaAc = new OpenFileDialog();
private void button1_Click(object sender, EventArgs e)
{
openFileDialogDosyaAc.Multiselect = true;
if (openFileDialogDosyaAc.ShowDialog() == DialogResult.OK)
{
dosyaYolu = openFileDialogDosyaAc.FileName;
bmp = new Bitmap(openFileDialogDosyaAc.FileNames.ToString());
pictureBox1.Image = bmp;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
private void button2_Click(object sender, EventArgs e)
{
Bitmap bmpKucuk = new Bitmap(pictureBox1.Image,Convert.ToInt32(textBox1.Text),Convert.ToInt32(textBox2.Text));
pictureBox1.Image = bmpKucuk;
pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
}
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "jpeg dosyası(*.jpg)|*.jpg|Bitmap(*.bmp)|*.bmp";
DialogResult sonuc = sfd.ShowDialog();
if (sonuc == DialogResult.OK)
{
pictureBox1.Image.Save(sfd.FileName);
}
}
}
}
Ok, so you are using winforms and want to open multiple files? or a directory? and want to resize them. but there is nothing resized? or do I need more coffee? use http://nuget.org/packages/ImageResizer/ and I don't see a loop to loop over the files you want to resize.
Read more about the imageresizer component here: http://imageresizing.net/docs/managed
in your button1 click event, do something like this:
private void button1_Click(object sender, EventArgs e)
{
DialogResult dr = this.openFileDialogDosyaAc.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
// Read the files
foreach (String file in openFileDialogDosyaAc.FileNames)
{
//resize and save
}
}
}

C# form instantly closing

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.

Categories