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));
Related
I am practicing an OCR program using C#, I am not much of a coder so I am trying to find my way around.
1- I OCR some pdf files.
2- I see the output of the OCR.
3- I use UI buttons to browse and then click convert.
4- I have a progress bar on the UI but it does not visually upgrade, while when I log the progressBar.Value I see its numbers are updating.
So I searched around and I found that the issue is I should like stop the thread and create a new one for the Ui to visually update, but I really do not understand that, or even do not know how to do it.
Can someone please help me ? like baby steps.
Also I know I have copied and pasted like alot of code for you to see.
The case is the following:
1- class fmMain: Form has a progressBarIncrementation function, responsible for taking the increment value from a function in processFunctions class.
2- progressBarIncrementation function has progressBar.Value to be updated, I see its value updated.
3- But visually nothing is updated. I tried some threading code, but i do not understand it so.....
class processFunctions
{
Thread newThread = Thread.CurrentThread;
private string invoiceNameIndex = "";
private string invoiceIBANIndex = "";
private string invoiceNumberIndex = "";
private string invoiceDateIndex = "";
private string invoiceSubtotalIndex = "";
private string invoiceVATIndex = "";
private string invoiceTotalIndex = "";
private string[] filePath;
private string[] fileNamePDF;
private int totalNumberOfFiles;
private string InformationNeeded(string wholeRead, string ix)
{
string[] lines = wholeRead.Split(new[] { "\r\n", "\r", "\n", " " }, StringSplitOptions.None);
if(ix.Contains(","))
{
string[] variableIndex = ix.Split(',');
string name = "";
for(int i =0; i < variableIndex.Length; i++)
{
name += lines[Convert.ToInt32(variableIndex[i])];
}
return name;
}
return lines[Convert.ToInt32(ix)];
}
public void ocrFunction(string filePathOnly)
{
var Ocr = new AutoOcr();
var Results = Ocr.ReadPdf(filePathOnly);
var Barcodes = Results.Barcodes;
var Text = Results.Text;
string[] numbers = { invoiceNameIndex, invoiceIBANIndex, invoiceNumberIndex,
invoiceDateIndex, invoiceSubtotalIndex, invoiceVATIndex, invoiceTotalIndex};
string[] results = new string[numbers.Count()];
for (int i = 0; i < numbers.Length; i++)
{
results[i] = InformationNeeded(Text, numbers[i]);
Console.WriteLine(results[i]);
}
Results = null;
Ocr = null;
Barcodes = null;
Text = null;
}
public int browseFile()
{
Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
OpenFileDialog ofd = new OpenFileDialog();
int numberOfFilesToBeProcessed = 0;
ofd.Filter = "PDF|*.pdf";
ofd.Multiselect = true;
string[] name = new string[2];
if (ofd.ShowDialog() == DialogResult.OK)
{
numberOfFilesToBeProcessed = ofd.FileNames.Length;
filePath = ofd.FileNames;
fileNamePDF = ofd.SafeFileNames;
}
this.totalNumberOfFiles = ofd.FileNames.Length;
return numberOfFilesToBeProcessed;
}
public void databaseReader()
{
string connectionString;
SqlConnection connection;
connectionString = ConfigurationManager.ConnectionStrings["OCR_App.Properties.Settings.LibraryConnectionString"].ConnectionString;
for (int i = 0; i < fileNamePDF.Length; i++)
{
string fileNameFiltered = fileNamePDF[i].Replace(".pdf", "");
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM invoicesTable WHERE invoiceRef = '" + fileNameFiltered + "'", connection))
{
DataTable invoicesTable = new DataTable();
adapter.Fill(invoicesTable);
DataRow index = invoicesTable.Rows[0];
invoiceNameIndex = (index[1].ToString());
invoiceIBANIndex = (index[2].ToString());
invoiceNumberIndex = (index[3].ToString());
invoiceDateIndex = (index[4].ToString());
invoiceSubtotalIndex = (index[5].ToString());
invoiceVATIndex = (index[6].ToString());
invoiceTotalIndex = (index[7].ToString());
ocrFunction(filePath[i]);
//newThread.Start();
fmMain formFunctions = new fmMain();
//Thread.Yield();
//Thread thread = new Thread(() => formFunctions.ProgressBarIncrementation(progressBarIncrement()));
formFunctions.ProgressBarIncrementation(progressBarIncrement());
}
}
}
public int progressBarIncrement()
{
int incrementValue = 0;
incrementValue = incrementValue + 100 / totalNumberOfFiles;
//Console.WriteLine(incrementValue);
return incrementValue;
}
///////////////////////////////////////////////////////////////////
public partial class fmMain : Form
{
processFunctions processingMain = new processFunctions();
ProgressBar NewprogressBar = new ProgressBar();
private static int incrementbar = 0;
public fmMain()
{
InitializeComponent();
}
[STAThread]
private void BtnBrowse_Click(object sender, EventArgs e)
//Browse the file needed to scan.
{
int number = processingMain.browseFile();
txtBoxFilePath.Text = number.ToString();
}
public void BtnConvert_Click(object sender, EventArgs e)
{
processingMain.databaseReader();
}
private void fmMain_Load(object sender, EventArgs e)
{
}
private void txtBoxFilePath_TextChanged(object sender, EventArgs e)
{
}
private void NumberOfFilesToBeProcessed_Click(object sender,
EventArgs e)
{
}
public void progressBar_Click(object sender, EventArgs e)
{
progressBar.Maximum = 100;
NewprogressBar.Value = progressBar.Value;
}
public void ProgressBarIncrementation(int incrementValue)
{
//Thread.Yield();
//Thread newThread = Thread.CurrentThread;
incrementbar = incrementbar + incrementValue;
progressBar.Visible = true;
progressBar.Value += incrementbar;
Thread thread = new Thread(() => progressBar.Value += incrementbar);
Console.WriteLine(progressBar.Value);
//progressBar.Value += incrementbar;
}
}
If you are needing the progress bar, you might want to consider creating an event to help report progress to your calling application. And you'll want to mark your function browseFile as async and do the following:
public async Task<int> browseFileAsync()
{
await Task.Run(new Action(() => {
OpenFileDialog ofd = new OpenFileDialog();
int numberOfFilesToBeProcessed = 0;
ofd.Filter = "PDF|*.pdf";
ofd.Multiselect = true;
string[] name = new string[2];
if (ofd.ShowDialog() == DialogResult.OK)
{
numberOfFilesToBeProcessed = ofd.FileNames.Length;
filePath = ofd.FileNames;
fileNamePDF = ofd.SafeFileNames;
}
this.totalNumberOfFiles = ofd.FileNames.Length;
return numberOfFilesToBeProcessed;
}));
}
And then in your calling application do:
private async void BtnBrowse_Click(object sender, EventArgs e)
//Browse the file needed to scan.
{
int number = await processMain.browseFileAsync();
txtBoxFilePath.Text = number.ToString();
}
I would also consider not calling a folder browser dialog from your class as this couples your class to a specific implementation. Rather, I would browse for the file from the GUI and pass the selected file(s) to the class.
I'm a student working on a GUI using C# Winforms, where the user is able to load an image, paint on it and then save the edited image to his system.
Bitmap b = new Bitmap(imgList);
image.DrawImage(b, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawImage(btm, Point.Empty);
My issue is when I save the edited image from the picturebox it's quality is reduced and it has the heightXwidth of that of the picturebox. I've provided my Form.cs below for reference. Is there any way I can make the edited image to maintain the image quality of the original image?
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SIP_UI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
imagelst = new ImageList();
}
//Declared Variables
private Graphics g;
private Graphics image;
private Bitmap btm;
private SolidBrush c;
private bool drawing = false;
private ImageList imagelst;
private string[] imglst;
private int imgCnt = 1;
private bool saveNxtWasClicked = false;
private bool savePrevWasClicked = false;
private void Form1_Load(object sender, EventArgs e)
{
g = pictureBox1.CreateGraphics();
btm = new Bitmap(pictureBox1.Width, pictureBox1.Height);
image = Graphics.FromImage(btm);
image.Clear(Color.White);
//Status color on default load
pnlStatus.BackColor = Color.DarkGray;
chkbxImageInfo.Checked = false;
if (chkbxImageInfo.Checked == false)
{
txtTestRep.Enabled = false;
txtBoard.Enabled = false;
cmbxPosition.Enabled = false;
}
btnNext.Enabled = true;
btnPrev.Enabled = false;
txtImgNum.Text = "0";
lblTotl.Text = "#";
using (StreamReader streamReaderOpen = new StreamReader("OpenLocation.txt"))
{
string strOpen = streamReaderOpen.ReadLine();
//Check path validity
if (System.IO.Directory.Exists(strOpen))
{
txtOpnPath.Text = strOpen;
}
else
{
txtOpnPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
}
}
using (StreamReader streamReaderSave = new StreamReader("SaveLocation.txt"))
{
string strSave = streamReaderSave.ReadLine();
//Check path validity
if (System.IO.Directory.Exists(strSave))
{
txtSavPath.Text = strSave;
}
else
{
txtSavPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
}
}
using (StreamReader streamReaderCsv = new StreamReader("CsvLocation.txt"))
{
string strCsv = streamReaderCsv.ReadLine();
//Check path validity
if (System.IO.Directory.Exists(strCsv))
{
txtCsvPath.Text = strCsv;
}
else
{
txtCsvPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
}
//Open images from previous folder
if (txtOpnPath.Text.Length > 0)
{
int i = 0;
int numImgs = Directory.GetFiles(txtOpnPath.Text, "*.PNG").Length;
imglst = new string[numImgs];
lblTotl.Text = Convert.ToString(numImgs);
txtImgNum.Text = Convert.ToString(1);
//foreach (var file in Directory.GetFiles(txtOpnPath.Text).Where(f => extensions.Contains(Path.GetExtension(f).ToUpper())))
foreach (var file in Directory.GetFiles(txtOpnPath.Text, "*.PNG"))
{
imglst[i++] = file;
}
if (imglst.Length > 0)
{
drawImage(imglst[0]);
//Added new
bool exist = Directory.EnumerateFiles(txtSavPath.Text, Path.GetFileNameWithoutExtension(imglst[0]) + "_MSKD*").Any();
if (exist)
{
pnlStatus.BackColor = Color.Red;
}
else
{
pnlStatus.BackColor = Color.Green;
}
}
else
{
MessageBox.Show("SELECT ANOTHER LOCATION", "NO SUPPORTED IMAGES FOUND", MessageBoxButtons.OK);
txtImgNum.Text = "0";
}
}
}
//Function to draw image into picturebox
private void drawImage(string imgList)
{
Bitmap b = new Bitmap(imgList);
image.DrawImage(b, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawImage(btm, Point.Empty);
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
drawing = false;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
drawing = true;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (drawing)
{
c = new SolidBrush(Color.Gray);
image.FillEllipse(c, e.X - (trackBar1.Value / 2), e.Y - (trackBar1.Value / 2), (trackBar1.Value * 15), (trackBar1.Value * 15));
g.DrawImage(btm, Point.Empty);
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
btnNext.Enabled = true;
lblTotl.Text = "#";
var fd = new System.Windows.Forms.FolderBrowserDialog();
if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int i = 0;
txtOpnPath.Text = fd.SelectedPath;
int numImgs = Directory.GetFiles(txtOpnPath.Text, "*.PNG").Length;
imglst = new string[numImgs];
lblTotl.Text = Convert.ToString(numImgs);
foreach (var file in Directory.GetFiles(txtOpnPath.Text, "*.PNG"))
{
imglst[i++] = file;
}
if (imglst.Length > 0)
{
drawImage(imglst[0]);
txtImgNum.Text = "1";
//Added new
bool exist = Directory.EnumerateFiles(txtSavPath.Text, Path.GetFileNameWithoutExtension(imglst[0]) + "_MSKD*").Any();
if (exist)
{
pnlStatus.BackColor = Color.Red;
}
else
{
pnlStatus.BackColor = Color.Green;
}
}
else
{
MessageBox.Show("SELECT ANOTHER LOCATION", "NO SUPPORTED IMAGES FOUND", MessageBoxButtons.OK);
pictureBox1.Image = null;
txtImgNum.Text = "0";
}
using (StreamWriter streamWriter = new StreamWriter("OpenLocation.txt"))
{
streamWriter.WriteLine(txtOpnPath.Text);
}
}
}
private void btnSaveFdr_Click(object sender, EventArgs e)
{
var savFoldr = new System.Windows.Forms.FolderBrowserDialog();
if (savFoldr.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtSavPath.Text = savFoldr.SelectedPath;
using (StreamWriter streamWriter = new StreamWriter("SaveLocation.txt"))
{
streamWriter.WriteLine(txtSavPath.Text);
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
saveNxtWasClicked = true;
savePrevWasClicked = true;
int count = 1;
imgCnt = Convert.ToInt32(txtImgNum.Text);
string imgPath = imglst[imgCnt - 1];
string fileName = Path.GetFileNameWithoutExtension(imgPath) + "_MSKD";
string fileExtnsn = Path.GetExtension(imgPath);
string filePath = txtSavPath.Text + "\\" + fileName + fileExtnsn;
while (File.Exists(filePath))
{
string tempFileName = string.Format("{0}({1})", fileName, count++);
filePath = Path.Combine(txtSavPath.Text, tempFileName + fileExtnsn);
}
btm.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
//Writing to CSV
string csvPath = txtCsvPath.Text + "\\CSVSpec.csv";
if (chkbxImageInfo.Checked == true)
{
if (File.Exists(csvPath))
{
// Initialise stream object with file
using (var wr = new StreamWriter(csvPath, true, Encoding.UTF8))
{
// Collection of image details
var row = new List<string>();
row.Add(Path.GetFileNameWithoutExtension(imgPath));
row.Add(txtTestRep.Text);
row.Add(txtBoard.Text);
row.Add(cmbxPosition.Text);
var sb = new StringBuilder();
foreach (string value in row)
{
// Add a comma before each string
if (sb.Length > 0)
{
sb.Append(",");
}
sb.Append(value);
}
wr.WriteLine(sb.ToString());
}
}
else
{
MessageBox.Show("Please add CSVSpec.csv file in specified location to save Image Information.", "MISSING: TEMPLATE FILE", MessageBoxButtons.OK);
}
}
else
{
}
DialogResult result = MessageBox.Show("IMAGE SAVED", "SAVE DIALOGUE", MessageBoxButtons.OK);
if (result == DialogResult.OK)
{
if (imgCnt != imglst.Length)
{
drawImage(imglst[imgCnt]);
imgCnt++;
txtImgNum.Text = Convert.ToString(imgCnt);
txtTestRep.Text = string.Empty;
txtBoard.Text = string.Empty;
cmbxPosition.SelectedIndex = 0;
saveNxtWasClicked = false;
}
else
{
btnNext.Enabled = false;
}
}
}
private void btnPrev_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtImgNum.Text);
btnNext.Enabled = true;
if (a > 1)
{
a = a - 2;
drawImage(imglst[a]);
txtImgNum.Text = Convert.ToString(a + 1);
txtTestRep.Text = string.Empty;
txtBoard.Text = string.Empty;
cmbxPosition.SelectedIndex = 0;
bool exist = Directory.EnumerateFiles(txtSavPath.Text, Path.GetFileNameWithoutExtension(imglst[a]) + "_MSKD*").Any();
if (exist)
{
pnlStatus.BackColor = Color.Red;
}
else
{
pnlStatus.BackColor = Color.Green;
}
}
else
{
btnPrev.Enabled = false;
}
}
private void btnNext_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtImgNum.Text);
btnPrev.Enabled = true;
if (imglst != null && a < imglst.Length)
{
drawImage(imglst[a++]);
txtImgNum.Text = Convert.ToString(a);
txtTestRep.Text = string.Empty;
txtBoard.Text = string.Empty;
cmbxPosition.SelectedIndex = 0;
bool exist = Directory.EnumerateFiles(txtSavPath.Text, Path.GetFileNameWithoutExtension(imglst[a - 1]) + "_MSKD*").Any();
if (exist)
{
pnlStatus.BackColor = Color.Red;
}
else
{
pnlStatus.BackColor = Color.Green;
}
}
else
{
btnNext.Enabled = false;
}
}
private void txtImgNum_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
int imgNum = Convert.ToInt32(txtImgNum.Text) - 1;
drawImage(imglst[imgNum]);
}
}
private void chkbxImageInfo_CheckedChanged(object sender, EventArgs e)
{
if (chkbxImageInfo.Checked)
{
txtTestRep.Enabled = true;
txtBoard.Enabled = true;
cmbxPosition.Enabled = true;
}
else
{
txtTestRep.Enabled = false;
txtBoard.Enabled = false;
cmbxPosition.Enabled = false;
}
}
private void btnClear_Click(object sender, EventArgs e)
{
int imgNum = Convert.ToInt32(txtImgNum.Text) - 1;
drawImage(imglst[imgNum]);
}
private void btnCsv_Click(object sender, EventArgs e)
{
var csvFoldr = new System.Windows.Forms.FolderBrowserDialog();
if (csvFoldr.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtCsvPath.Text = csvFoldr.SelectedPath;
using (StreamWriter streamWriter = new StreamWriter("CsvLocation.txt"))
{
streamWriter.WriteLine(txtCsvPath.Text);
}
}
}
}
}
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 ?
This question already has answers here:
File being used by another process after using File.Create()
(11 answers)
Closed 6 years ago.
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 Newtonsoft.Json;
namespace Youtube_Player
{
public partial class Authentication : Form
{
public static string AuthenticationApplicationDirectory;
public static string AuthenticationFileName = "Authentication.txt";
StreamWriter w;
public static bool formclosed = false;
static Authentication()
{
AuthenticationApplicationDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "Authentication";
if (!Directory.Exists(AuthenticationApplicationDirectory))
{
Directory.CreateDirectory(AuthenticationApplicationDirectory);
}
AuthenticationFileName = Path.Combine(AuthenticationApplicationDirectory, AuthenticationFileName);
if (!File.Exists(AuthenticationFileName))
File.Create(AuthenticationFileName);
}
public Authentication()
{
InitializeComponent();
cTextBox1.Text = Form1.AuthenticationValues.ApiKey;
cTextBox2.Text = Form1.AuthenticationValues.UserId;
cTextBox3.Text = Form1.AuthenticationValues.JsonFileDirectory;
label1.Visible = false;
button1.Enabled = false;
button4.Enabled = false;
cTextBox2.WaterMarkForeColor = Color.Blue;
cTextBox3.WaterMarkForeColor = Color.Green;
cTextBox2.WaterMarkActiveForeColor = Color.Blue;
cTextBox3.WaterMarkActiveForeColor = Color.Green;
cTextBox1.ForeColor = Color.Red;
cTextBox2.ForeColor = Color.Blue;
cTextBox3.ForeColor = Color.Green;
cTextBox1.WaterMark = "Enter Api Key";
cTextBox2.WaterMark = "Enter Email Account";
cTextBox3.WaterMark = "Browse To The Json File Location";
}
private void Authentication_Load(object sender, EventArgs e)
{
}
private void cTextBox1_TextChanged(object sender, EventArgs e)
{
if (cTextBox1.Text != "Enter Api Key" && cTextBox1.Text != "")
{
button1.Enabled = true;
}
else
{
button1.Enabled = false;
}
}
private void cTextBox2_TextChanged(object sender, EventArgs e)
{
if (cTextBox2.Text != "Enter Email Account" && cTextBox2.Text != "")
{
button4.Enabled = true;
}
else
{
button4.Enabled = false;
}
}
private void cTextBox3_TextChanged(object sender, EventArgs e)
{
if (cTextBox3.Text != "Browse To The Json File Location" && cTextBox3.Text != "")
button6.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Confirmed";
button1.Enabled = false;
label1.Text = "Updating Settings File";
label1.Visible = true;
if (label1.Visible == true)
{
button6.Enabled = false;
button4.Enabled = false;
button1.Enabled = false;
}
FileInfo fi = new FileInfo(AuthenticationFileName);
if (fi.Length == 0)
{
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("Api" + "=" + cTextBox1.Text);
w.Close();
}
else
{
w = new StreamWriter(AuthenticationFileName);
w.WriteLine("Api" + "=" + cTextBox1.Text);
w.Close();
}
timer1.Start();
}
private void button4_Click(object sender, EventArgs e)
{
button4.Enabled = false;
label1.Text = "Updating Settings File";
label1.Visible = true;
if (label1.Visible == true)
{
button6.Enabled = false;
button4.Enabled = false;
button1.Enabled = false;
}
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("UserId" + "=" + cTextBox2.Text);
w.Close();
timer1.Start();
}
private void button6_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Json Files (*.json)|*.json";
openFileDialog1.FilterIndex = 0;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
cTextBox3.BackColor = Color.White;
cTextBox3.ForeColor = Color.Green;
cTextBox3.Text = openFileDialog1.FileName;
label1.Text = "Updating Settings File";
label1.Visible = true;
if (label1.Visible == true)
{
button6.Enabled = false;
button4.Enabled = false;
button1.Enabled = false;
}
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("JsonFileDirectory" + "=" + cTextBox3.Text);
w.Close();
timer1.Start();
}
}
private void button2_Click(object sender, EventArgs e)
{
ResetValues(true);
}
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
count += 1;
if (count == 2)
{
label1.Visible = false;
timer1.Stop();
count = 0;
}
}
private void Authentication_FormClosing(object sender, FormClosingEventArgs e)
{
ResetValues(false);
}
private void ResetValues(bool DeleteFile)
{
cTextBox1.Text = "";
cTextBox2.Text = "";
cTextBox3.Text = "";
button1.Text = "Confirm";
button4.Text = "Confirm";
button6.Enabled = true;
timer1.Stop();
count = 0;
if (DeleteFile == true)
{
if (File.Exists(AuthenticationFileName))
File.Delete(AuthenticationFileName);
}
Form1.AuthenticationValues.ApiKey = "";
Form1.AuthenticationValues.JsonFileDirectory = "";
Form1.AuthenticationValues.UserId = "";
if (Form1.AuthenticationValues.AuthenticationMenu.Enabled
== false && (Form1.lines.Length < 3 && Form1.lines.Length > 0))
Form1.AuthenticationValues.AuthenticationMenu.Enabled = true;
formclosed = true;
}
}
}
The first problem is in the constructor when checking for the file existing:
if (!File.Exists(AuthenticationFileName))
File.Create(AuthenticationFileName);
This make the file to be busy in use. When later in my code i'm trying to use the file again to write to it i'm getting exception that the file is in use by another process.
The second problem is in the 3 places i'm trying to write to the file.
The first place:
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("Api" + "=" + cTextBox1.Text);
w.Close();
Then under it in another place in the code i'm writing again to the file:
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("UserId" + "=" + cTextBox2.Text);
w.Close();
And last:
w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("JsonFileDirectory" + "=" + cTextBox3.Text);
w.Close();
The problems are first the file is busy in use since the checking if exist i'm doing in the constructor.
The second problem is that i want to make that if in the file there is no line that start with "Api" then write the Api part:
w.WriteLine("Api" + "=" + cTextBox1.Text);
But if it does exist and the text is changed in the textBox cTextBox1.Text i want to write to the file the changed text to the place where the Api line is. And to append a new Api line.
Same for all two other places i'm writing to the file.
If i will make it all false not to appen when writing it will write one line each time and will overwrite the line.
But if i'm doing true it will append many Api lines or many UserId lines.
And i want each to time to replace the line with the textBox to overwrite only on this line but with the new text.
If in cTextBox1 there is the text: Hello World
Then i changed it to: Hello World Now
Then replace the Api line Hello World with Hello World Now
Alright, addressing your main concern:
File.CreateFile actually opens a filestream for you to use. Easiest way to solve this is to do File.CreateFile().Close() to close it when you're done.
Next, you are trying to change data in a file, but you never read it to find the information.
You can look up StreamReader and use that, and parse out data and figure out what's where, but there's a much more obvious choice: Just re-write all of the information every time.
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;
}