How to make Proxy Checker faster - c#

I made a simple proxy checker but the problem is it is very slow. It takes much time because it checks one after one. I want to make it check +10 proxies in the same time. The question is: How can I make it fast using threads.
This is the simplified code :
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void addgood() {
int co = int.Parse(bunifuCustomLabel1.Text);
co++;
bunifuCustomLabel1.Text = co.ToString();
}
public void testProxy(string ip, int port)
{
bool OK = false;
try
{
WebClient wc = new WebClient();
wc.Proxy = new WebProxy(ip, port);
wc.DownloadString("http://google.com/ncr");
OK = true;
addgood();
richTextBox2.Text +=ip+":"+port+"\n";
}
catch { }
}
private void bunifuFlatButton1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "TXT Files | *.txt";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fileName = openFileDialog1.FileName;
proxy_list.Text = File.ReadAllText(#fileName);
proxy_list.Refresh();
}
}
private void bunifuFlatButton4_Click(object sender, EventArgs e)
{
String ip;
int port;
if (proxy_list.Lines.Length < 1)
{
MessageBox.Show("Proxy list is Vide");
}
else {
foreach(String i in proxy_list.Lines){
String[] tab = i.Split(':');
port = int.Parse(tab[1]);
ip = tab[0];
testProxy(ip , port);
}
}
}
}
}

Here is an async implementation to your testProxy:
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void addgood()
{
int co = int.Parse(bunifuCustomLabel1.Text);
co++;
bunifuCustomLabel1.Text = co.ToString();
}
public async Task testProxy(string ip, int port)
{
bool OK = false;
try
{
WebClient wc = new WebClient();
wc.Proxy = new WebProxy(ip, port);
await wc.DownloadStringTaskAsync(new Uri("http://google.com/ncr"));
OK = true;
addgood();
richTextBox2.Text += ip + ":" + port + "\n";
}
catch { }
}
private void bunifuFlatButton1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "TXT Files | *.txt";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fileName = openFileDialog1.FileName;
proxy_list.Text = File.ReadAllText(#fileName);
proxy_list.Refresh();
}
}
private void bunifuFlatButton4_Click(object sender, EventArgs e)
{
if (proxy_list.Lines.Length < 1)
{
MessageBox.Show("Proxy list is Vide");
}
else
{
var asyncTasks = new Task[proxy_list.Lines.Length];
for (int i = 0; i < proxy_list.Lines.Length; i++)
{
var tab = proxy_list.Lines[i].Split(':');
asyncTasks[i] = testProxy(tab[0], int.Parse(tab[1]));
}
Task.WaitAll(asyncTasks);
}
}
}
}

Related

Logging Modbus Data to XML

currently I am facing some difficulties in developing the code to log modbus data into XML format instead of CSV in c#. Following is the code which I have done:
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
InitializeRegisters();
}
private void FormMain_Load(object sender, EventArgs e)
{
try
{
//Start Modbus RTU Service
ModbusRTUProtocol.Start();
timer1.Enabled = true;
//HMI Display (Label) Controls
displayControl1.Register = ModbusRTUProtocol.Registers[0];
displayControl2.Register = ModbusRTUProtocol.Registers[1];
displayControl3.Register = ModbusRTUProtocol.Registers[2];
//HMI Editor Controls
editorControl1.Register = ModbusRTUProtocol.Registers[3];
editorControl2.Register = ModbusRTUProtocol.Registers[4];
editorControl3.Register = ModbusRTUProtocol.Registers[5];
editorControl4.Register = ModbusRTUProtocol.Registers[6];
editorControl5.Register = ModbusRTUProtocol.Registers[7];
editorControl6.Register = ModbusRTUProtocol.Registers[8];
editorControl7.Register = ModbusRTUProtocol.Registers[9];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
ModbusRTUProtocol.Stop();
Application.DoEvents();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void InitializeRegisters()
{
ModbusRTUProtocol.Registers.Clear();
ModbusRTUProtocol.Registers.Add(new Register() { Address = 0 });
ModbusRTUProtocol.Registers.Add(new Register() { Address = 1 });
ModbusRTUProtocol.Registers.Add(new Register() { Address = 2 });
ModbusRTUProtocol.Registers.Add(new Register() { Address = 3 });
ModbusRTUProtocol.Registers.Add(new Register() { Address = 4 });
ModbusRTUProtocol.Registers.Add(new Register() { Address = 5 });
ModbusRTUProtocol.Registers.Add(new Register() { Address = 6 });
ModbusRTUProtocol.Registers.Add(new Register() { Address = 7 });
ModbusRTUProtocol.Registers.Add(new Register() { Address = 8 });
ModbusRTUProtocol.Registers.Add(new Register() { Address = 9 });
}
private void bttnSetEC_Click(object sender, EventArgs e)
{
if (bttnSetEC.Text == "Set EC")
{
bttnSetEC.Text = "Lock Setting";
editorControl1.Enabled = true;
editorControl2.Enabled = true;
editorControl3.Enabled = true;
}
else if (bttnSetEC.Text == "Lock Setting")
{
bttnSetEC.Text = "Set EC";
editorControl1.Enabled = false;
editorControl2.Enabled = false;
editorControl3.Enabled = false;
}
}
private void bttnSetpH_Click(object sender, EventArgs e)
{
if (bttnSetpH.Text == "Set pH")
{
bttnSetpH.Text = "Lock Setting";
editorControl4.Enabled = true;
editorControl5.Enabled = true;
editorControl6.Enabled = true;
}
else if (bttnSetpH.Text == "Lock Setting")
{
bttnSetpH.Text = "Set pH";
editorControl4.Enabled = false;
editorControl5.Enabled = false;
editorControl6.Enabled = false;
}
}
private void bttnPumpAutoOn_Click(object sender, EventArgs e)
{
if (bttnPumpAutoOn.Text == "Set Pump Automation")
{
bttnPumpAutoOn.Text = "Lock Pump Setting";
editorControl7.Enabled = true;
}
else if (bttnPumpAutoOn.Text == "Lock Pump Setting")
{
bttnPumpAutoOn.Text = "Set Pump Automation";
editorControl7.Enabled = false;
}
}
private void WriteLogInformation(string filename, string info1, string info2)
{
StringBuilder sbuilder = new StringBuilder();
using (StringWriter sw = new StringWriter(sbuilder))
{
using (XmlTextWriter w = new XmlTextWriter(sw))
{
w.WriteStartElement("LogInfo");
w.WriteElementString("Time", DateTime.Now.ToString());
w.WriteElementString("Info1", info1);
w.WriteElementString("Info2", info2);
w.WriteEndElement();
}
}
using (StreamWriter w = new StreamWriter(filename, true, Encoding.UTF8))
{
w.WriteLine(sbuilder.ToString());
}
}
private void timer1_Tick(object sender, EventArgs e)
{
string filename = #"c:\modbustest.xmllog";
//private static FileStream fs = new FileStream(#"c:\temp\mcb.txt", FileMode.OpenOrCreate, FileAccess.Write);
try
{
XmlSerializer x = new XmlSerializer(ModbusRTUProtocol.Registers[0]);
//WriteLogInformation(filename, string.Format(ModbusRTUProtocol.Registers[0]), string.Format("pH {0}", ModbusRTUProtocol.Registers[1]));
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error");
}
}
This is the part which I stuck on:
private void timer1_Tick(object sender, EventArgs e)
{
string filename = #"c:\modbustest.xmllog";
//private static FileStream fs = new FileStream(#"c:\temp\mcb.txt", FileMode.OpenOrCreate, FileAccess.Write);
try
{
XmlSerializer x = new XmlSerializer(ModbusRTUProtocol.Registers[0]);
//WriteLogInformation(filename, string.Format(ModbusRTUProtocol.Registers[0]), string.Format("pH {0}", ModbusRTUProtocol.Registers[1]));
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error");
}
}
I am trying to read the coil and output the data read into xml logging file. However this is where I stuck on, can't get the it output the data into XML.
Can anyone please help me in this?
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication189
{
class Program
{
const string FILENAME = #"C:\temp\test.xml";
static void Main(string[] args)
{
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Modbus></Modbus>";
XDocument doc = XDocument.Parse(xml);
XElement modbus = doc.Root;
modbus.Add(new XElement("Register0", ModbusRTUProtocol.Registers[0]));
doc.Save(FILENAME);
}
}
}

Pass HTML id in another web form

I try to display crystal report in Report.aspx. so for this first i create class "``report_class` and in that class i create function like this:
using cookies
in webform2 i try this
public static bool setCookiesValue(Page page, string cookiesName, string cookiesValue, ref string ermsg)
{
if (cookiesValue.Trim().Length < 1)
{
ermsg = "cookies empty";
return false;
}
HttpCookie clearCookies = page.Request.Cookies[cookiesName];
clearCookies[cookiesName] = cookiesValue;
clearCookies.Expires = DateTime.Now.AddDays(1d);
page.Response.Cookies.Add(clearCookies);
return true;
}
public static String getCookies(Page page, string cookiesName)
{
try
{
HttpCookie GetCookies = page.Request.Cookies[cookiesName];
return GetCookies[cookiesName].ToString();
}
catch (Exception er)
{
return string.Empty;
}
}
then on button click
protected void Button6_Click(object sender, EventArgs e)
{
try
{
string datef = string.Empty;
setCookiesValue(this, "fromdate", "todate","regiondrop", ref ret);
report_class r = new report_class();
Report_Detail report = new Report_Detail();
Response.Redirect("Reports.aspx");
}
catch
{
Label4.Visible = true;
}
}
and in reports.aspx
protected void Page_Load(object sender, EventArgs e)
{
Report_Detail report = new Report_Detail();
report_class r = new report_class();
string date_f = getCookies(this, "fromdate");
string date_t = getCookies(this, "todate");
string drop_r = getCookies(this, "regiondrop");
r.Bindreport_class(report, Convert.ToDateTime(date_f),
Convert.ToDateTime(date_t), Convert.ToString(drop_r));
CrystalReportViewer1.ReportSource = report;
CrystalReportViewer1.DataBind();
}
but this show error
Error 8 No overload for method 'setCookiesValue' takes 5 arguments
Error 3 The name 'getCookies' does not exist in the current context
You just need to pass the value from for Example form1 to form2:
Do it this way:
FORM2
public partial class Form2 : Form
{
public static Label lblvar= null;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
FORM1:
public partial class Form1 : Form
{
public Form1()
{
Form2.lblvar = lblvarinform1;
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
lblvarinform1.Text = txtdatepicker.Text;
Form2.lblvar.Text = lblvarinform1.Text;
}
}
USING COOKIES:
public static bool setCookiesValue(Page page, string cookiesName, string cookiesValue,ref string ermsg)
{
if (cookiesValue.Trim().Length < 1)
{
ermsg = "cookies empty";
return false;
}
HttpCookie clearCookies = page.Request.Cookies[cookiesName];
clearCookies[cookiesName] = cookiesValue;
clearCookies.Expires = DateTime.Now.AddDays(1d);
page.Response.Cookies.Add(clearCookies);
return true;
}
public static String getCookies(Page page,string cookiesName)
{
try
{
HttpCookie GetCookies = page.Request.Cookies[cookiesName];
return GetCookies[cookiesName].ToString();
}
catch (Exception er)
{
return string.Empty;
}
}
using the function above:
set cookies new value:
string ret = string.Empty;
setCookiesValue(this,"yourcookiesname","thisisyourdatevaue_or_any",ref ret);
get cookies value in another form:
string getval = getCookies(this,"yourcookiesname");

Image Gallery on C#

What I have to do is this:
Make an image gallery that has 5 buttons which each one select a folder of images.
Other two buttons for next and previous of the folder you are in. In my line 76, it says
argument 1: cannot convert from 'System.collection.Generic.list' to string
Any ideas?
Here's an image of the console
http://postimg.org/image/nct5pwdit/
Line 76 says:
pictureBox1.Load(semestres[semac].imagen[]);
I have the same command like 6 times.
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;
class semestres
{
public List<string> imagen = new List<string>();
private int _semestre;
public int canti;
public int actual;
public int c;
public semestres(int semestre, List<string> imagenes)
{
_semestre = semestre;
imagen = imagenes;
c = imagen.Count;
actual = 0;
}
public int semestre
{
get
{
return _semestre;
}
set
{
c = imagen.Count;
}
}
public int can
{
get
{
return c;
}
set
{
c = imagen.Count;
}
}
}
namespace Visor
{
public partial class Form1 : Form
{
private int cont;
private int semac;
private int _cant;
private int next;
private List<semestres> semestres = new List<semestres>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
cont = semestres[semac].actual;
cont--;
if (cont >= 0)
{
pictureBox1.Load(semestres[semac].imagen[]);
semestres[semac].actual = cont;
}
else
{
// MessageBox("Esta es la primer imagen");
cont = 0;
semestres[semac].actual = cont;
pictureBox1.Load(semestres[semac].imagen);
}
}
private void button7_Click(object sender, EventArgs e)
{
cont = semestres[semac].actual;
next = semestres[semac].c;
cont++;
if (cont < next)
{
pictureBox1.Load(semestres[semac].imagen);
semestres[semac].actual = cont;
}
else
{
// MessageBox("Esta es la ultima imagen");
cont--;
semestres[semac].actual = cont;
pictureBox1.Load(semestres[semac].imagen(cont));
}
}
private void button2_Click(object sender, EventArgs e)
{
semac = 0;
try
{
if (semestres[0].c > 0)
{
cont = semestres[0].actual;
pictureBox1.Load(semestres[0].imagen(cont));
}
}
catch (Exception)
{
OpenFileDialog file = new OpenFileDialog();
file.InitialDirectory = #"C:\";
file.Filter = "Images (*.BMP; *.JPG; *.GIF)|*.BMP; *.JPG; *.GIF|" + "All files(*.*)|*.*";
file.FilterIndex = 1;
file.Multiselect = true;
file.RestoreDirectory = true;
file.ShowDialog();
string[] imgs = file.FileNames;
List<string> imagenes = new List<string>();
foreach (string imagen in imgs)
{
imagenes.Add(imagen);
}
semestres.Add(new semestres(1, imagenes));
pictureBox1.Load(imagenes[0]);
semestres[0].actual = 0;
cont = 0;
}
}
private void button6_Click(object sender, EventArgs e)
{
}
private void btn_3_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_sal_Click(object sender, EventArgs e)
{
}
private void btn_2_Click(object sender, EventArgs e)
{
}
}
}
So you have this:
pictureBox1.Load(semestres[semac].imagen);
Well the problem is that imagen is a List<string>. Picturebox.Load(string) takes a string, not a List<string>. So you need to get a string from that list instead of passing the whole list. One way would be:
pictureBox1.Load(semestres[semac].imagen[0]);
This would load the first image in that list.
Alternatively, you might be trying to do:
pictureBox1.Load(semestres[semac].imagen[cont]);
You just need to determine what the correct index is that you're trying to specify.

Why is the backgroundworker not pausing when I click the button?

In Form1 I removed/deleted the _busy variable. In Form1 top I did:
BackgroundWebCrawling bgwc;
Then in the button4 pause click event I did:
private void button4_Click(object sender, EventArgs e)
{
bgwc.PauseWorker();
label6.Text = "Process Paused";
button5.Enabled = true;
button4.Enabled = false;
}
In the button5 click event button I did:
private void button5_Click(object sender, EventArgs e)
{
bgwc.ContinueWorker();
label6.Text = "Process Resumed";
button4.Enabled = true;
button5.Enabled = false;
}
And the cancel button click event:
private void button3_Click(object sender, EventArgs e)
{
bgwc.CancelWorker();
cancel = true;
}
Then I'm checking in Form1 completed event if cancel is true or not:
if (cancel == true)
{
label6.Text = "Process Cancelled";
}
else
{
label6.Text = "Process Completed";
}
And this is how the BackgroundWebCrawling class look like now:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using System.Net;
using System.Windows.Forms;
using System.ComponentModel;
using System.Threading;
namespace GatherLinks
{
class BackgroundWebCrawling
{
public string f;
int counter = 0;
List<string> WebSitesToCrawl;
int MaxSimultaneousThreads;
public BackgroundWorker mainBackGroundWorker;
BackgroundWorker secondryBackGroundWorker;
WebcrawlerConfiguration webcrawlerCFG;
List<WebCrawler> webcrawlers;
int maxlevels;
public event EventHandler<BackgroundWebCrawlingProgressEventHandler> ProgressEvent;
ManualResetEvent _busy = new ManualResetEvent(true);
public BackgroundWebCrawling()
{
webcrawlers = new List<WebCrawler>();
mainBackGroundWorker = new BackgroundWorker();
mainBackGroundWorker.WorkerSupportsCancellation = true;
mainBackGroundWorker.DoWork += mainBackGroundWorker_DoWork;
}
private void mainBackGroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 0; i < WebSitesToCrawl.Count; i++)
{
_busy.WaitOne();
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
while (counter >= MaxSimultaneousThreads)
{
Thread.Sleep(10);
}
WebCrawler wc = new WebCrawler(webcrawlerCFG);
webcrawlers.Add(wc);
counter++;
secondryBackGroundWorker = new BackgroundWorker();
secondryBackGroundWorker.DoWork += secondryBackGroundWorker_DoWork;
object[] args = new object[] { wc, WebSitesToCrawl[i] };
secondryBackGroundWorker.RunWorkerAsync(args);
}
while (counter > 0)
{
Thread.Sleep(10);
}
}
private void secondryBackGroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
object[] args = (object[])e.Argument;
WebCrawler wc = (WebCrawler)args[0];
string mainUrl = (string)args[1];
wc.ProgressEvent += new EventHandler<WebCrawler.WebCrawlerProgressEventHandler>(x_ProgressEvent);
wc.webCrawler(mainUrl, maxlevels);
counter--;
}
public void Start(List<string> sitestocrawl, int threadsNumber, int maxlevels, WebcrawlerConfiguration wccfg)
{
this.maxlevels = maxlevels;
webcrawlerCFG = wccfg;
WebSitesToCrawl = sitestocrawl;
MaxSimultaneousThreads = threadsNumber;
mainBackGroundWorker.RunWorkerAsync();
}
private void x_ProgressEvent(object sender, WebCrawler.WebCrawlerProgressEventHandler e)
{
// OK .. so now you get the data here in e
// and here you should call the event to form1
Object[] temp_arr = new Object[8];
temp_arr[0] = e.csFiles;
temp_arr[1] = e.mainUrl;
temp_arr[2] = e.levels;
temp_arr[3] = e.currentCrawlingSite;
temp_arr[4] = e.sitesToCrawl;
temp_arr[5] = e.done;
temp_arr[6] = e.failedUrls;
temp_arr[7] = e.failed;
OnProgressEvent(temp_arr); /// Send the data + additional data from this class to Form1..
///
/*
* temp_arr[0] = csFiles;
temp_arr[1] = mainUrl;
temp_arr[2] = levels;
temp_arr[3] = currentCrawlingSite;
temp_arr[4] = sitesToCrawl;*/
}
private void GetLists(List<string> allWebSites)
{
}
public class BackgroundWebCrawlingProgressEventHandler : EventArgs
{
public List<string> csFiles { get; set; }
public string mainUrl { get; set; }
public int levels { get; set; }
public List<string> currentCrawlingSite { get; set; }
public List<string> sitesToCrawl { get; set; }
public bool done { get; set; }
public int failedUrls { get; set; }
public bool failed { get; set; }
}
protected void OnProgressEvent(Object[] some_params) // Probably you need to some vars here to...
{
// some_params to put in evenetArgs..
if (ProgressEvent != null)
ProgressEvent(this,
new BackgroundWebCrawlingProgressEventHandler()
{
csFiles = (List<string>)some_params[0],
mainUrl = (string)some_params[1],
levels = (int)some_params[2],
currentCrawlingSite = (List<string>)some_params[3],
sitesToCrawl = (List<string>)some_params[4],
done = (bool)some_params[5],
failedUrls = (int)some_params[6],
failed = (bool)some_params[7]
});
}
public void PauseWorker()
{
if (mainBackGroundWorker.IsBusy)
{
_busy.Reset();
}
}
public void ContinueWorker()
{
_busy.Set();
}
public void CancelWorker()
{
ContinueWorker();
mainBackGroundWorker.CancelAsync();
}
}
}
So I added the methods the pause the continue the cancel. In the dowork event, I changed all the things and added things.
But when I click the buttons there is no effect. Not pausing, not continue and not cancel. Nothing.
You never check the _busy status in mainBackGroundWorker_DoWork method;
for (int i = 0; i < WebSitesToCrawl.Count; i++)
{
_busy.WaitOne();
//...
}
also you should have your ManualResetEvent _busy in class with BackgroundWorker
ManualResetEvent _busy = new ManualResetEvent(true);
public BackgroundWorker mainBackGroundWorker;
public void PauseWorker()
{
if(mainBackGroundWorker.IsBusy)
{
_busy.Reset();
}
}
public void ContinueWorker()
{
_busy.Set();
}
and in Form1:
private void button4_Click(object sender, EventArgs e)
{
bgwc.PauseWorker();
//...
}
private void button5_Click(object sender, EventArgs e)
{
bgwc.ContinueWorker();
//...
}
to cancel the BackgroundWorker you can use CancellationPending property and CancelAsync method. Note: you should first unpause the worker.
public void CancelWorker()
{
ContinueWorker();
mainBackGroundWorker.CancelAsync();
}
private void mainBackGroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 0; i < WebSitesToCrawl.Count; i++)
{
_busy.WaitOne();
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
//...
}
}
If this doesn't help you, then you have problems with mainBackGroundWorker code and secondryBackGroundWorker.
This code only pauses mainBackGroundWorker, but not secondryBackGroundWorkers. The same with cancelation. If main worker is canceled? it will wait for all the secondary workers to finish their jobs. Also if you pause main worker? you can still have new results arriving from secondary workers.
You do not handle errors. If you have an exception in second worker, than you do not get any notification about that and also your main worker will never stop, because counter will never be 0.
There can be another problems, witch cause this behaviour.

how to use the browse folder dialog in console application

I created a program that monitors what happens to the files inside a directory. For example if I add a new file, it shows the path and the name of the new file. Though I coded it in Windows Forms, I want to change it to a Console Application so that it shows the results on the console
My question is that how can I browse a folder using a console?
any ideas thanks in advance
The Windows Forms code is below:
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
button1.Enabled = false;
button2.Enabled = true;
directoryPath = folderBrowserDialog1.SelectedPath;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
if (Directory.Exists(directoryPath))
{
textbox_append("monitor opened");
filesList = Directory.GetFiles(directoryPath);
timer1.Start();
}
else
{
MessageBox.Show("folder does not exist.");
}
}
catch (Exception ex)
{
MessageBox.Show("Error." + ex.Message);
}
}
this is my whole code
namespace emin_lab2_Csharp
{
public partial class Form1 : Form
{
public string directoryPath;
string[] filesList, filesListTmp;
IFileOperation[] opList = { new FileProcByExt("jpeg"),
new FileProcByExt("jpg"),
new FileProcByExt("doc"),
new FileProcByExt("pdf"),
new FileProcByExt("djvu"),
new FileProcNameAfter20()
};
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
button1.Enabled = false;
button2.Enabled = true;
directoryPath = folderBrowserDialog1.SelectedPath;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
if (Directory.Exists(directoryPath))
{
textbox_append("monitor opened");
filesList = Directory.GetFiles(directoryPath);
timer1.Start();
}
else
{
MessageBox.Show("Такой папки нету.");
}
}
catch (Exception ex)
{
MessageBox.Show("Error." + ex.Message);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
filesListTmp = Directory.GetFiles(directoryPath);
foreach (var elem in Enumerable.Except<string>(filesListTmp, filesList))
{
textbox_append(elem);
foreach (var op in opList)
{
if (op.Accept(elem)) { op.Process(elem); textbox_append(elem + " - action is performed on the file"); }
}
}
filesList = filesListTmp;
}
public void textbox_append(string stroka)
{
textBox1.AppendText(stroka);
textBox1.AppendText(Environment.NewLine);
}
interface IFileOperation
{
bool Accept(string fileName);
void Process(string fileName);
}
class FileProcByExt : IFileOperation
{
string extName;
string folderName;
public FileProcByExt(string ext = "")
{
extName = ext;
folderName = extName.ToUpper();
}
public bool Accept(string fileName)
{
bool res = false;
if (Path.GetExtension(fileName) == "." + extName) res = true;
return res;
}
public void Process(string fileName)
{
Directory.CreateDirectory(Path.Combine(Path.GetDirectoryName(fileName),
folderName));
File.Move(fileName,
Path.Combine(Path.GetDirectoryName(fileName),
folderName,
Path.GetFileName(fileName)));
}
}
class FileProcNameAfter20 : IFileOperation
{
public bool Accept(string fileName)
{
return Path.GetFileNameWithoutExtension(fileName).Length > 20;
}
public void Process(string fileName)
{
int cnt = Path.GetFileNameWithoutExtension(fileName).Length;
File.Copy(fileName,
Path.Combine(Path.GetDirectoryName(fileName),
"longname_" + cnt + Path.GetExtension(fileName)));
}
}
}
}
First, you need to add reference to System.Windows.Forms
Second, add STAThread attribute to your method.
For example:
using System;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
[STAThread]
static void Main(string[] args)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
Console.Write(ofd.FileName);
}
}
}

Categories

Resources