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);
}
}
}
Related
I'm doing winforms app that can automatically run the Wooting-Double-Movement when Fortnite is running, but I need to thread the function. I can't thread it by System.Threading.Tasks. I tried to use Thread.Start and Thread.Abort but Thread.Abort doesn't work in .NET Core 5.0. So, how can I do this?
Button4 is start button and Button5 is stop
using System;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using System.Threading.Tasks;
namespace AutoDoubleMovement
{
public partial class Form1 : Form
{
static OpenFileDialog ofd = new OpenFileDialog();
static Settings Settings = new Settings();
static Info Info = new Info();
static string path = $#"C:\Users\{Environment.UserName}\AppData\Local\AutoWDM";
static string file = $#"{path}\WDM_path.txt";
static string file_wdm = File.ReadAllText(file);
// Threading this function
public static void WDM()
{
while (true)
{
string wdm_path = File.ReadAllText(file);
Process[] fortnite = Process.GetProcessesByName("FortniteClient-Win64-Shipping");
Process[] wdm = Process.GetProcessesByName("wooting-double-movement");
ProcessStartInfo wdmproc = new ProcessStartInfo() { FileName = wdm_path };
foreach (Process _wdm in wdm)
{
if (fortnite.Length != 0)
{
if (wdm.Length == 0)
{
Process.Start(wdmproc);
}
}
else
{
if (wdm.Length != 0)
{
_wdm.Kill();
}
}
Thread.Sleep(1000);
}
}
}
public Form1()
{
InitializeComponent();
Settings.Owner = this;
}
private void button1_Click(object sender, EventArgs e)
{
if (ofd.ShowDialog() != DialogResult.Cancel)
{
textBox1.Text = ofd.FileName;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
if (Directory.Exists(path))
{
File.WriteAllText(file, ofd.FileName);
}
}
else
{
File.WriteAllText(file, ofd.FileName);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
Settings.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
Info.ShowDialog();
}
// This is the button to start threading WDM
private void button4_Click(object sender, EventArgs e)
{
if (!textBox1.Text.Contains("wooting-double-movement.exe"))
{
MessageBox.Show("Your path doesn't contain \"wooting-double-movement.exe\" file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
button1.Enabled = false;
button4.Enabled = false;
button5.Enabled = true;
}
}
// This is the button to stop threading WDM
private void button5_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button4.Enabled = false;
button5.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists(file))
{
textBox1.Text = file_wdm;
}
}
}
}
And if you didn't understand something, sorry for that, I'm not American
DO NOT USE static OpenFileDialog ofd = new OpenFileDialog(); Make dialogs only with using () { }
Try not Task but normal Thread, with .Start() and .Abort()
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);
}
}
}
I try to do some minimal app for myself and I have a little problem with selected path. I have the following code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void FilesCountNumberShow_button_Click(object sender, RoutedEventArgs e)
{
// Try to count nu,ber of files in folder
int fCount = Directory.GetFiles(count_path, "*", SearchOption.TopDirectoryOnly).Length;
FilesCountNumber_Label.Content = "Files in folder: " + fCount;
}
private void SelectFolderPath_button_Click(object sender, RoutedEventArgs e)
{
// These code is for open File Dialog and choose older path as count_path
var SelectFolderPath_Dialog = new WinForms.FolderBrowserDialog();
if (SelectFolderPath_Dialog.ShowDialog() == WinForms.DialogResult.OK)
{
string count_path = SelectFolderPath_Dialog.SelectedPath;
MessageBox.Show(count_path);
}
}
}
}
How can I reference the variable count_path in
int fCount = Directory.GetFiles(count_path, "*", SearchOption.TopDirectoryOnly).Length;
I have information that it isn't exist (I think is locla variable in SelectFolderPath_button_Click right? How can I set it global?
I do something that. I add string count_path { get; set; } there:
public partial class MainWindow : Window
{
string count_path { get; set; }
public MainWindow()
{
InitializeComponent();
}
and modify
private void SelectFolderPath_button_Click(object sender, RoutedEventArgs e)
{
var SelectFolderPath_Dialog = new WinForms.FolderBrowserDialog();
if (SelectFolderPath_Dialog.ShowDialog() == WinForms.DialogResult.OK)
{
count_path = SelectFolderPath_Dialog.SelectedPath;
MessageBox.Show(count_path);
}
}
Is this good solution or should it be otherwise done?
Store the selected path in a private field and validate that it has been set:
public partial class MainWindow : Window
{
private string count_path;
public MainWindow()
{
InitializeComponent();
}
private void FilesCountNumberShow_button_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(count_path))
{
MessageBox.Show("You must select a folder first!");
}
else
{
// Try to count nu,ber of files in folder
int fCount = Directory.GetFiles(count_path, "*", SearchOption.TopDirectoryOnly).Length;
FilesCountNumber_Label.Content = "Files in folder: " + fCount;
}
}
private void SelectFolderPath_button_Click(object sender, RoutedEventArgs e)
{
// These code is for open File Dialog and choose older path as count_path
var SelectFolderPath_Dialog = new WinForms.FolderBrowserDialog();
if (SelectFolderPath_Dialog.ShowDialog() == WinForms.DialogResult.OK)
{
count_path = SelectFolderPath_Dialog.SelectedPath;
MessageBox.Show(count_path);
}
}
}
//add assembly reference System.Windows.Forms
private void SelectFolderPath_button_Click(object sender, RoutedEventArgs e)
{
using (var SelectFolderPath_Dialog = new System.Windows.Forms.FolderBrowserDialog())
{
if (SelectFolderPath_Dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string count_path = SelectFolderPath_Dialog.SelectedPath;
MessageBox.Show(count_path);
}
}
}
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);
}
}
}
}
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");