Function is not running and creating the text file - c#

I created the function pro:
it contains the process array
it calls another write function to make the file and write into it.
the write function writeproc:
it checks if the file at specified path is present or not.
if not it generates the file else it appends the text into the file.
when i run the code it is not doing anything.... :(
This is the main method for the console app that i have made in c#.
[STAThread]
static void Main(String[] args)
{
pro();
}
pro function:
static void pro()
{
Process[] localAll = Process.GetProcesses();
String path_pro = "C://KEYLOGS//processes.txt";
foreach(Process proc in localAll)
{
writeproc(path_pro, proc);
}
}
writeproc function:
static void writeproc(String p, Process the_process)
{
if (!File.Exists(p))
{
using (StreamWriter sw = File.CreateText(p))
{
//empty file generated.
}
}
else
{
using (StreamWriter sw = File.AppendText(p))
{
sw.WriteLine("Process: "+the_process);
}
}
}

This may be the cause of two different things.
1: The folder does not exist on your C drive so the file can't be created. (It will throw a System.IO.DirectoryNotFoundException)
Add Directory.CreateDirectory(p); to the start of your writeproc method.
2: You don't have enough rights to write to your C drive. (It will throw a System.UnauthorizedAccessException)
I suggest adding a breakpoint in your writeproc method to see what exception is being thrown.

Related

is there a method to SelfUpdate a console application in MSVSC C# .net5

I'm develop a simple Console Application c# (GT-AutoPatcher.exe) with MSVSC2022 .NET5 capable of update some files in windows systems, include itselfs. The problem is, when i try to update the "updater" (the created app called GT-AutoPatcher.exe) i get stucked because i dont know the correct way to update a running program...
I'm trying this
using (WebClient web1 = new WebClient()) {
web1.Headers.Add("user-agent", "Other");
web1.DownloadFile("http://*/","GT-AutoPatcher.exe");
}
But result is:
Unhandled exception. System.Net.WebException: An exception occurred during a WebClient request.
---> System.IO.IOException: The process cannot access the file 'C:\*\bin\Debug\net5.0\GT-AutoPatcher.exe' because it is being used by another process.
Reasons:
The console application is running. How can i close it to donwload a new version?
If you want to close the program, you can refer to this code:
public static class Program1
{
static void Main(string[] args)
{
CloseApp("your file type");//Change this to what you want to turn off
}
private static void CloseApp(string ArrayProcessName)
{
string[] processName = ArrayProcessName.Split(',');
foreach (string appName in processName)
{
Process[] localByNameApp = Process.GetProcessesByName(appName);//Get all processes with program name
if (localByNameApp.Length > 0)
{
foreach (var app in localByNameApp)
{
if (!app.HasExited && app.MainWindowTitle == "your file name")
{
app.Kill();//close the process
}
}
}
}
}
}

Overwriting a txt file

I have a problem writing the file: I call the app launch via the API and get its status in string.
using System;
using System.Threading.Tasks;
using UiPath.Robot.Api;
using System.Linq;
using System.IO;
namespace RobotApi
{
class Program
{
static TextWriter sw = new StreamWriter("d:\\robo\\log.txt", true, System.Text.Encoding.Default);
static async Task Main(string[] args)
{
var client = new RobotClient();
var processes = await client.GetProcesses();
var myProcess = processes.Single(process => process.Name == "MyProcess");
var job = myProcess.ToJob();
job.StatusChanged += (sender, args) => sw.WriteLine($"{((Job)sender).ProcessKey}: {args.Status}");
await client.RunJob(job);
}
}
}
I need to write the job status to a txt file for later analysis. Since the program is called asynchronously, I can't use the StreamWritter, since it simply can't be closed. File.WriteAllText just can't handle such a flow of information and doesn't have time to close the file, as a result, I get an error message that txt is being used by another process.
Please tell me, is there a way to write a large stream of information to a txt file in my case (it is necessary that the string is overwritten with each status update)?
I believe that your problem is just with the lambda expression and you don't know how to get more statements inside it except the WriteLine() call.
A solution would be to define a regular method instead of the lambda expression.
namespace RobotApi
{
class Program
{
// <-- removed the StreamWriter here
static async Task Main(string[] args)
{
var client = new RobotClient();
var processes = await client.GetProcesses();
var myProcess = processes.Single(process => process.Name == "MyProcess");
var job = myProcess.ToJob();
job.StatusChanged += OnStatusChanged; // <-- refer to the method here
await client.RunJob(job);
}
// This method is new
// Assuming StatusEventArgs
void OnStatusChanged(object sender, StatusEventArgs args)
{
// using will close the file
using (TextWriter sw = new StreamWriter("d:\\robo\\log.txt", true, System.Text.Encoding.Default))
{
sw.WriteLine($"{((Job)sender).ProcessKey}: {args.Status}");
}
}
}
}
This implementation is not thread safe, but your implementation wasn't either, so I don't care at the moment.
sw (from TextWriter) is statically global to the program object... I do not see where it is being CLOSED... you write to it on the async threading calls... but never close it... never flush it...
And of course (unless I missed something) never overwrite it with a new open call... so there is never the intended overwrite????

FolderBrowserDialog won't show in a single .cs file without Form

I am trying to code a program which is executed when a file is right clicked in windows, and then a context menu feature named 'Move to' executes a file in the windows registry HKEY ClASSES. It ought to parse in "%1" as argument when it executes, so that my program knows where the file is located. However, when I compile my single .cs file, the FolderBrowserDialog won't show. I am suspecting that it is because I haven't initialized some kind of form before I call it. Is it possible in some way to choose a folder from a single c# file without including Forms?
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
public class MoveTo : Form
{
public static string current_file_path;
public static string new_file_path;
public static string file_name;
public static void Main(string[] args){
if (args.Length > 0)
{
current_file_path = (string) args[0];
file_name = (string) current_file_path.Replace(Path.GetDirectoryName(Environment.GetCommandLineArgs()[1]), "");
var browser = new FolderBrowserDialog();
if (browser.ShowDialog()==DialogResult.OK)
{
new_file_path = browser.SelectedPath + file_name;
}else
{
Environment.Exit(1);
}
try
{
File.Move(current_file_path, new_file_path);
}catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
If you bypass the argument check and try to show the FBD in a debugger, with this exact code, you will see System.Threading.ThreadStateException: 'Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.'
As per the error message, this exception won't be raised if no debugger is attached. Put an [STAThread] attribute on your Main method, like you normally see in any windows forms app:
[STAThread]
public static void Main(string[] args)
{
...
I also recommend you add an else for your outer if, to show an error if no arguments are passed (otherwise your app will exit silently

Notepad (app created in c#) don't read text at start

I have a simple notepad with a rich text box. I have build the project to see if it works. I can open files with openFileDialog or save files with saveFileDialog.
The problem is :
if I set this notepad to by default program to open text files on windows, text doesn't appear in the notepad.
how can I make a function to read text when I open notepad.
UPDATE: If i set my notepad to by default text editor on the Windows i can open the notepad, and i can open or save files. The problem appear when i open a text file directly from the desktop/explorer. When i double click to the file, My Notepad is opening, but the text from the file not appear.
I am beginner at programmer, so any kind of help will be much appreciated.
I am trying to use this as constructor:
using (StreamWriter w = new StreamWriter(file))
{
w.Write(patch);
w.Close();
}
But this is not working. I know I need a function when program start, but I don't know how can I write it.
The filename you double-click on in Explorer will be passed as an args parameter to your notepad app. So you can get the file path like this:
public static void Main(string[] args){
string path = args[0];
Application.Run(new Notepad(path));
}
Here is an application that will read text from file if it is set as default file reader or if you drag-and-drop file to this app EXE.
This is console app but you should grasp a concept.
using System;
using System.IO;
namespace SampleFileOpener
{
class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
if (File.Exists(arg))
{
Console.WriteLine(); //Empty line
var content = File.ReadAllText(arg);
Console.WriteLine(content);
Console.WriteLine(); //Empty line
}
}
Console.ReadLine();
}
}
}
In Form.cs (that contains designer), you can add this:
public void readOnOpen(string fileName)
{
path = fileName;
if (File.Exists(path))
{
// Write to file
textBox1.Text = File.ReadAllText(path);
}
}
In program.cs, you can add this:
[STAThread]
static void Main(string[] args)
{
//check whether you get this by double-clicking file or debug with compiler
if (args != null && args.Length > 0)
{
//if args is not NULL, it means you do it by double-clicking files
//so, you can get the filename by getting the args
string fileName = args[0];
//Check file exists
if (File.Exists(fileName))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 MainForm = new Form1();
//this would call method open (like with open dialogue)
//you can get path or filename from args in Main Form
//MainForm is your notepad form
MainForm.readOnOpen(fileName);
Application.Run(MainForm);
}
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}

After updating EnvironmentVariable - PATH - I still get a FileNotFoundException on Windows 2003 Server

I'm just starting with a new product and I guess I don't understand the PATH variable. My documentation says to update the PATH like this which I do successfully in a little console application:
using HP.HPTRIM.SDK;
namespace TestSDKforTRIM71
{
class Program
{
static void Main(string[] args)
{
string trimInstallDir = #"C:\Program Files\Hewlett-Packard\HP TRIM";
string temp = Environment.GetEnvironmentVariable("PATH") + ";" + trimInstallDir;
Environment.SetEnvironmentVariable("PATH", temp);
DoTrimStuff();
}
public static void DoTrimStuff()
{
using (Database db = new Database())
{
db.Connect();
Console.WriteLine(db.Id);
}
Console.ReadKey();
}
}
}
In the above project, I have a reference to HP.HPTRIM.SDK which exists at:
C:\Program Files\Hewlett-Packard\HP TRIM\HP.HPTRIM.SDK.dll
After the above ran successfully, I tried to permanently change the PATH by using Control Panel:System:Advanced:Environment Variables. I verified the above PATH by examining the registry at HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment. I see the following as the last entry in the PATH value:
;C:\Program Files\Hewlett-Packard\HP TRIM\
I thought this would permanently SET this at the end of the PATH but when I run the above console program with a few lines commented out I get the FileNotFoundException (see below). I am confused about how to get this in the PATH and not have to worry about it anymore.
using HP.HPTRIM.SDK;
namespace TestSDKforTRIM71
{
class Program
{
static void Main(string[] args)
{
//string trimInstallDir = #"C:\Program Files\Hewlett-Packard\HP TRIM";
//string temp = Environment.GetEnvironmentVariable("PATH") + ";" + trimInstallDir;
//Environment.SetEnvironmentVariable("PATH", temp);
DoTrimStuff(); // without setting the PATH this fails despite being in REGISTRY...
}
public static void DoTrimStuff()
{
using (Database db = new Database())
{
db.Connect();
Console.WriteLine(db.Id);
}
Console.ReadKey();
}
}
}
Only newly started processes that don't inherit their environment from their parent will have the updated PATH. You'll have to at least restart the Visual Studio hosting process, close and re-open your solution. To cover all possible corners, log out and log back in so that Windows Explorer (and thus Visual Studio) also start using the updated environment.

Categories

Resources