Is there a much better way for me to streamWrite without needing to repeat the code for every button I press? Below is an example I am working on where one button does it's own thing and writes accordingly to vowels and the other does the same thing except it writes accordingly for no alpha characters:
private void btnVowels_Click(object sender, EventArgs e)
{
string wholeText = "";
string copyText = richTextBox1.Text;
if (System.IO.File.Exists(Second_File) == true)
{
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(Second_File);
string vowels = "AaEeIiOoUu";
copyText = new string(copyText.Where(c => !vowels.Contains(c)).ToArray());
wholeText = richTextBox1.Text + copyText;
objWriter.Write(wholeText);
richTextBox2.Text = wholeText;
objWriter.Close();
}
else
{
MessageBox.Show("No file named " + Second_File);
}
}
private void btnAlpha_Click(object sender, EventArgs e)
{
string wholeText = "";
string copyText = richTextBox1.Text;
if (System.IO.File.Exists(Second_File) == true)
{
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(Second_File);
string nonAlpha = #"[^A-Za-z ]+";
string addSpace = "";
copyText = Regex.Replace(copyText, nonAlpha, addSpace);
objWriter.Write(wholeText);
richTextBox2.Text = wholeText;
objWriter.Close();
}
else
{
MessageBox.Show("No file named " + Second_File);
}
}
You could use a common function that will take care of writing the contents to the file and updating the second textbox:
private void btnAlpha_Click(object sender, EventArgs e)
{
string nonAlpha = #"[^A-Za-z ]+";
string addSpace = "";
string copyText = richTextBox1.Text;
copyText = Regex.Replace(copyText, nonAlpha, addSpace);
WriteToFile(Second_File, wholeText);
}
private void btnVowels_Click(object sender, EventArgs e)
{
string vowels = "AaEeIiOoUu";
string copyText = richTextBox1.Text;
copyText = new string(copyText.Where(c => !vowels.Contains(c)).ToArray());
string wholeText = richTextBox1.Text + copyText;
WriteToFile(Second_File, wholeText);
}
private void WriteToFile(string filename, string contents)
{
if (File.Exists(filename))
{
File.WriteAllText(filename, contents);
richTextBox2.Text = wholeText;
}
else
{
MessageBox.Show("No file named " + filename);
}
}
why not doing it this way?
private void Write(string file, string text)
{
if (File.Exists(file))
{
using (StreamWriter objWriter = new StreamWriter(file))
{
objWriter.Write(text);
}
}
else
{
MessageBox.Show("No file named " + file);
}
}
private void btnAlpha_Click(object sender, EventArgs e)
{
string wholeText = "";
string copyText = richTextBox1.Text;
string nonAlpha = #"[^A-Za-z ]+";
string addSpace = "";
copyText = Regex.Replace(copyText, nonAlpha, addSpace);
wholeText = richTextBox1.Text + copyText;
Write(Second_File, wholeText); // same for the second button
richTextBox2.Text = wholeText;
}
Related
My user can create a file name that goes to a specific directory path(Textbox3) and they can change the directory path(TextBox4), I am having trouble reading Textbox4 which is the changing the path textbox.
It reads textbox3 just fine and does everything i need it to do if there is a filename in the textbox but when i put something in textbox4 it is not reading it.
private void textBox3_TextChanged(object sender, EventArgs e) //reads fine, file goes to C:\\Temp
{
string textBoxContents = textBox3.Text;
}
private void textBox4_TextChanged(object sender, EventArgs e)//this is not required, this is only if they want to change where the file is going Ex:(D:\\Test
{
string textBoxContents = textBox4.Text;
}
private void button1_Click(object sender, EventArgs e)
{
string Filename = textBox3.Text.Substring(0) + ".txt";
string Filepath = textBox4.Text.Substring(0) + ".txt";
var files = Directory.GetFiles(#"C:\\Temp").Length;
string path2 = Path.GetFullPath("C:\\Temp");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string var = Path.Combine(docPath, path2);
string var1 = Path.Combine(var, Filename);
using (StreamWriter objWriter = new StreamWriter(var1))
{
int numpins = int.Parse(textBox1.Text);
string basepin = textBox2.Text;
int pinlength = basepin.Length;
string formatspecifier = "{0:d" + pinlength.ToString() + "}" + "{1}";
long pinnumber = long.Parse(basepin);
string dig = textBox2.Text;
string result = GetCheckDigit(dig);
objWriter.WriteLine($"These are the Bin ranges");
objWriter.WriteLine();
for (int d = 0; d < numpins; d++)
{
if (String.IsNullOrEmpty(dig))
{
throw new Exception("null value not allowed");
}
else
{
dig = pinnumber.ToString();
result = GetCheckDigit(dig);
}
basepin = string.Format(formatspecifier, pinnumber, result);
objWriter.WriteLine(basepin);
pinnumber++;
}
objWriter.Close();
MessageBox.Show("File has been created");
}
}
Guys i have modem Wavecom Fasttrack Supreme, and i want make program to receive the SMS instantly, so when i send sms the sms go to my listview1
and i have code like that
public ReciveEmail()
{
InitializeComponent();
getAvaliblePorts();
}
private void button1_Click(object sender, EventArgs e)
{
baca_sms();
}
private void baca_sms()
{
serialPort1.Parity = Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
serialPort1.Handshake = Handshake.XOnXOff;
serialPort1.DtrEnable = true;
serialPort1.RtsEnable = true;
serialPort1.NewLine = Environment.NewLine;
serialPort1.Write("AT" + System.Environment.NewLine);
Thread.Sleep(1000);
serialPort1.WriteLine("AT+CMGF=1" + System.Environment.NewLine);
Thread.Sleep(1000);
serialPort1.WriteLine("AT+CMGL=\"ALL\"\r" + System.Environment.NewLine);
Thread.Sleep(3000);
MessageBox.Show(serialPort1.ReadExisting());
Regex r = new Regex(#"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");// own creation you must learn
Match m = r.Match(serialPort1.ReadExisting());
while (m.Success)
{
// ShortMessage msg = new ShortMessage();
string a = m.Groups[1].Value;
string b = m.Groups[2].Value;
string c = m.Groups[3].Value;
string d = m.Groups[4].Value;
string ee = m.Groups[5].Value;
string f = m.Groups[6].Value;
// MessageBox.Show(f);
ListViewItem item = new ListViewItem(new string[] { a, b, c, d, ee, f });
listView1.Items.Add(item);
m = m.NextMatch();
}
}
public void getAvaliblePorts()
{
String[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "")
{
MessageBox.Show("Please Check your choice !!");
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.Open();
progressBar1.Value = 100;
btnClose.Enabled = true;
btnRead.Enabled = true;
btnOpen.Enabled = false;
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("UnauthorizedAccessException");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
serialPort1.Close();
progressBar1.Value = 0;
btnRead.Enabled = false;
btnClose.Enabled = false;
btnOpen.Enabled = true;
}
and when i Click button Read the serialport always give me "OK OK OK", why no have Message go in ? any problem my AT Command ? or something ?
We are just making a small quiz with TCP server. We can connect one client to the server but with multiple the server crashes. Ignore the dutch in it.
It can be that there are some non-logic things in it cause we have been playing with it for some hours.
Our code for the server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Diagnostics;
namespace Simpele_Server
{
class Program
{
const int portNr = 2000;
static void Main(string[] args)
{
Program obj = new Program();
string antwoord = "";
string client1Ant = "";
string client2Ant = "";
string client3ant = "";
System.Net.IPAddress localAddress = System.Net.IPAddress.Parse("10.145.4.43");
//Luister op het eigen IP-adres: 127.0.0.1 (Loop back adres)
TcpListener mijnListener = new TcpListener(localAddress, portNr);
mijnListener.Start();
Console.WriteLine("\n Wachten op verbinding...\n");
while (true)
{
//Aanvaard het binnenkomende verzoek
TcpClient eenClient = mijnListener.AcceptTcpClient();
//Gebruik een 'NetworkStream object' om gegevens te verzenden en te ontvangen
NetworkStream ns = eenClient.GetStream();
byte[] data = new byte[eenClient.ReceiveBufferSize];
//Lees de binnenkomende 'stream' --> Read() is een 'blocking call'
int numBytesRead = ns.Read(data, 0,System.Convert.ToInt32(eenClient.ReceiveBufferSize));
antwoord = Encoding.ASCII.GetString(data, 0, numBytesRead);
if (antwoord.Substring(0, 8).Equals("Client1:"))
{
client1Ant = antwoord;
Console.WriteLine(obj.ControleerAntwoorden1(client1Ant));
}
if (antwoord.Substring(0, 8).Equals("Client2:"))
{
client1Ant = antwoord;
Console.WriteLine(obj.ControleerAntwoorden2(client2Ant));
}
if (antwoord.Substring(0, 8).Equals("Client3:"))
{
client1Ant = antwoord;
Console.WriteLine(obj.ControleerAntwoorden3(client3ant));
}
//Beeld de ontvangen data af
Console.WriteLine("Ontvangen: " + antwoord);
}
//Voorkom onmiddellijk sluiten van het venster
Console.ReadLine();
}
private int ControleerAntwoorden1(string antwoord)
{
int punten = 0;
string antw;
antw = antwoord.Replace("Client1:", "");
//antw = antwoord.Replace("Client2:", "");
//antw = antwoord.Replace("Client3:", "");
Console.WriteLine(antw);
string ant1 = antw.Substring(0, 1);
string ant2 = antw.Substring(1, 1);
string ant3 = antw.Substring(2, 1);
string ant4 = antw.Substring(3, 1);
if (ant1.Equals("1"))
punten++;
if (ant2.Equals("2"))
punten++;
if (ant3.Equals("3"))
punten++;
if (ant4.Equals("4"))
punten++;
return punten;
}
private int ControleerAntwoorden2(string antwoord)
{
int punten = 0;
string antw;
//antw = antwoord.Replace("Client1:", "");
antw = antwoord.Replace("Client2:", "");
//antw = antwoord.Replace("Client3:", "");
Console.WriteLine(antw);
string ant1 = antw.Substring(0, 1);
string ant2 = antw.Substring(1, 1);
string ant3 = antw.Substring(2, 1);
string ant4 = antw.Substring(3, 1);
if (ant1.Equals("1"))
punten++;
if (ant2.Equals("2"))
punten++;
if (ant3.Equals("3"))
punten++;
if (ant4.Equals("4"))
punten++;
return punten;
}
private int ControleerAntwoorden3(string antwoord)
{
int punten = 0;
string antw;
//antw = antwoord.Replace("Client1:", "");
//antw = antwoord.Replace("Client2:", "");
antw = antwoord.Replace("Client3:", "");
Console.WriteLine(antw);
string ant1 = antw.Substring(0, 1);
string ant2 = antw.Substring(1, 1);
string ant3 = antw.Substring(2, 1);
string ant4 = antw.Substring(3, 1);
if (ant1.Equals("1"))
punten++;
if (ant2.Equals("2"))
punten++;
if (ant3.Equals("3"))
punten++;
if (ant4.Equals("4"))
punten++;
return punten;
}
}
}
Our client:
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.Net.Sockets;
namespace client
{
public partial class Form1 : Form
{
const int poortNr = 2000;
//string ipadres = "127.0.0.1";
string ipadres = "10.145.4.43";
string strRead = null;
int intBytesRead;
string[] vragen = { "1. In welk jaar is 9/11 gebeurt?" + Environment.NewLine + " A = 2001" + Environment.NewLine + " B = 2000 " + Environment.NewLine + " C = 1999" + Environment.NewLine + " D = 1998",
"2. Welke kleur heeft een wolk?" + Environment.NewLine + " A = Blauw " + Environment.NewLine + " B = Groen " + Environment.NewLine + " C = Wit " + Environment.NewLine + " D = geel",
"3. Leeft Steve Jobs nog? " + Environment.NewLine + " A = Nee " + Environment.NewLine + " B = Ja " + Environment.NewLine + " C = Steve jobs heeft nooit bestaan " + Environment.NewLine + " D = test",
"4. test"};
string antwoorden = "";
int counter;
int aantalcounter = 2;
int vraagnr = 0;
TcpClient mijnClient = new TcpClient();
private void startTimer()
{
counter = aantalcounter;
timer1.Start();
timer1.Interval = 1000;
}
private void resetTimer()
{
counter = aantalcounter;
timer1.Stop();
timer1.Start();
}
private void stopTimer()
{
timer1.Stop();
}
public NetworkStream getNS()
{
//networkstream
NetworkStream mijnNS = mijnClient.GetStream();
return mijnNS;
}
public void disableRadiobuttons()
{
radioButton1.Enabled = false;
radioButton2.Enabled = false;
radioButton3.Enabled = false;
radioButton4.Enabled = false;
}
public void uncheckRadiobuttons()
{
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
}
//verzend data naar server
public void verzendData(string tekst)
{
byte[] aDataTeVersturen = Encoding.ASCII.GetBytes(tekst);
getNS().Write(aDataTeVersturen, 0, aDataTeVersturen.Length);
}
//zoek selected antwoord
public string getAntwoord()
{
string qsdf = "Client1: ";
string answer = "";
if (radioButton1.Checked == true)
{
answer = "1";
}
if (radioButton2.Checked == true)
{
answer = "2";
}
if (radioButton3.Checked == true)
{
answer = "3";
}
if (radioButton4.Checked == true)
{
answer = "4";
}
if (radioButton1.Checked == false && radioButton2.Checked == false && radioButton3.Checked == false && radioButton4.Checked == false)
{
answer = "0"; //geen antwoord
}
qsdf += answer;
return qsdf;
}
//alle antwoorden opslaan in lange string
public void opslaanAntwoorden(string antwoord)
{
antwoorden += antwoord;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
txtVraag.Text = vragen[vraagnr];
startTimer();
try
{
mijnClient.Connect(ipadres, poortNr);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnVerbreek_Click(object sender, EventArgs e)
{
getNS().Close();
mijnClient.Close();
Application.Exit();
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void txtAntwoord_TextChanged(object sender, EventArgs e)
{
}
private void btnOntvang_Click(object sender, EventArgs e)
{
//data van server krijgen
byte[] aDataOntvangen = new byte[Convert.ToInt32(mijnClient.ReceiveBufferSize)];
intBytesRead = getNS().Read(aDataOntvangen, 0, Convert.ToInt32(mijnClient.ReceiveBufferSize));
strRead = Encoding.ASCII.GetString(aDataOntvangen, 0, intBytesRead);
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void txtVraag_TextChanged(object sender, EventArgs e)
{
}
private void timer1_Tick_1(object sender, EventArgs e)
{
txtCount.Text = counter.ToString();
counter--;
if (counter == -1)
{
resetTimer();
startTimer();
opslaanAntwoorden(getAntwoord()); //antwoorden opslaan in 1 lange string
if (vraagnr != vragen.Length-1)
{
txtVraag.Text = vragen[vraagnr + 1];
volgendeVraag();
uncheckRadiobuttons();
}
else
{
verzendData(antwoorden); //zend alle antwoorden (einde van quiz)
txtVraag.Text = "Einde van quiz";
uncheckRadiobuttons();
disableRadiobuttons();
//timer op 0 + stoppen
stopTimer();
counter = 0;
txtCount.Text = counter.ToString();
}
}
}
private void volgendeVraag()
{
vraagnr++;
}
private void label2_Click(object sender, EventArgs e)
{
}
private void radioButton4_CheckedChanged(object sender, EventArgs e)
{
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void lblCount_Click(object sender, EventArgs e)
{
}
}
}
i have a AsyncFileUpload control :
<asp:AsyncFileUpload ID="venfileupld" runat="server" OnUploadedComplete="ProcessUpload" />
on its OnUploadedComplete event i am writing this code :
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string name = venfileupld.FileName.ToString();
string filepath = "upload_excel/" + name;
venfileupld.SaveAs(Server.MapPath(name));
}
now i have to read the content of the uploaded file ... i have a function for that:
public void writetodb(string filename)
{
string[] str;
string vcode = "";
string pswd = "";
string vname = "";
StreamReader sr = new StreamReader(filename);
string line="";
while ((line = sr.ReadLine()) != null)
{
str = line.Split(new char[] { ',' });
vcode = str[0];
pswd = str[1];
vname = str[2];
insertdataintosql(vcode, pswd, vname);
}
lblmsg4.Text = "Data Inserted Sucessfully";
}
now my query is that how i can get the uploaded file to pass to this function ?
UPDATE
i have done this :
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string name = venfileupld.FileName.ToString();
string filepath = "upload_excel/" + name;
venfileupld.SaveAs(Server.MapPath(name));
string filename = System.IO.Path.GetFileName(e.FileName);
writetodb(filepath);
}
but getting an error... file not found
I'm not sure if i have understood the problem, but isn't it easy as:
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string name = System.IO.Path.GetFileName(e.filename);
string dir = Server.MapPath("upload_excel/");
string path = Path.Combine(dir, name);
venfileupld.SaveAs(path);
writetodb(path);
}
SaveAs will save the file on the server, so you can do what you want with it afterwards.
it doest work:<, here is my code:
public void buttonSaveTo_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowDialog();
richTextBox1.Text = fbd.SelectedPath;
string destination = fbd.SelectedPath;
}
and this is how i try to save files
{
webClient.DownloadFile("http://i.imgur.com/" + picture, #"destionation" + picture);
}
EDIT// okay thanks for answers but it still doesnt work:<, maybe im doing omething wrong, look this is all code i wrote
namespace Imgur
{
public partial class Form1 : Form
{
bool flag = true;
int downloadedNumber = 0;
public Form1()
{
InitializeComponent();
}
public void buttonStart_Click(object sender, EventArgs e)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
if (!flag)
{
flag = true;
}
for (int i=0;i<100000 && flag;i++)
{
WebClient webClient = new WebClient();
string pic1 = rnd_str(5);
string pic2 = ".jpg";
string picture = pic1 + pic2;
//********** GETTING SIZE OF IMAGE ***********
Size sz = GetSize("http://i.imgur.com/" + picture);
string imageSize = (sz.Width.ToString() + " " + sz.Height.ToString()); ;
//********************************************
if(imageSize != "161 81")
{
webClient.DownloadFile("http://i.imgur.com/" + picture, destination + picture);
richTextBox1.Text += String.Format("Downloaded picture: {0}\r\n", picture);
downloadedNumber++;
textBoxDownloadedNumber.Text = string.Format("{0}", downloadedNumber);
}
webClient.Dispose();
Application.DoEvents();
if (i == 999995)
{
flag = false;
}
}
richTextBox1.Text += "theend\n";
buttonStart.Enabled = true;
buttonStop.Enabled = false;
}
public static Size GetSize(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Accept = "image/gif";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
Bitmap bmp = new Bitmap(s);
Size sz = new Size(bmp.Width, bmp.Height);
return sz;
}
public static string rnd_str(int liczba_liter)
{
Random r = new Random();
int char_type;
string return_string = "";
int i =0;
for (i = 0; i < liczba_liter; i++)
{
if (r.Next(1, 3) == 1)
{
char_type = r.Next(1, 4);
switch (char_type)
{
case 1:
return_string += (char)r.Next(48, 58); // convertion int -> ASCII character; 48-57 are ASCII digits
break;
case 2:
return_string += (char)r.Next(97, 123); // convertion int -> ASCII character; as above but small letters
break;
case 3:
return_string += (char)r.Next(65, 91); // as above; large letters
break;
default:
i -= 1;
break;//do not add any letter if no type is allowed
}
}
else
{
i -= 1;
return_string += "";
}
}
return return_string;
}
private void buttonStop_Click(object sender, EventArgs e)
{
flag = false;
buttonStart.Enabled = true;
}
public void buttonSaveTo_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowDialog();
richTextBox1.Text = fbd.SelectedPath;
string destination = fbd.SelectedPath;
}
}
}
You are currently just concatenating strings, but your folder name probably does not end with a directory separator char. Assuming picture is the file name of your picture (e.g. foo.jpg) use Path.Combine() instead to let the framework do the work for you:
var localFileName = Path.Combine(destination, picture);
webClient.DownloadFile("http://i.imgur.com/" + picture, localFileName);
Your "destination" in the DownloadFile-Call is a string and not the actual variable. Also the destination variable must be on class level. SOmthing like:
private string destination;
public void buttonSaveTo_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowDialog();
richTextBox1.Text = fbd.SelectedPath;
destination = fbd.SelectedPath;
}
webClient.DownloadFile("http://i.imgur.com/" + picture, System.IO.Path.Combine(destionation, picture));