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

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());
}

Related

C# Console app need assistance with main args error

I have the following c# Console app I would run this in ssis but i am using a couple of PDF manipulating librarys. so i am going to call an exe from my ssis package while passing in a file path.
But i am getting the following error when trying to run via the exe.
Unhandled Exception: System.IndexOutOfRangeException: Index was
outside the bounds of the array. at ConsoleApp.program.Main(String[]
args) line 87
BUT if i run in debug it works fine. Once i get it working on its own via the exe, i want to pass the filepath as a parameter in ssis.
see c# below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.util;
using System.IO;
namespace PDF_Read_ConsoleApp
{
class Program
{
public static void FilePath(string path)
{
//Console.WriteLine("Please enter full pdf path \n\n ");
//path = Console.ReadLine();
string fp;
fp = #path;
string[] files = Directory.GetFiles(path, "*.pdf");
foreach (string s in files)
{
string txtOutput = s.Replace(".pdf", ".txt");
if (File.Exists(txtOutput))
{
File.Delete(txtOutput);
}
string output;
PDDocument doc = null;
try
{
doc = PDDocument.load(s);
PDFTextStripper stripper = new PDFTextStripper();
stripper.getText(doc);
output = stripper.getText(doc);
StreamWriter NewFile;
NewFile = new StreamWriter(txtOutput);
//NewFile.Write(output.ToString());
NewFile.Write(output.ToString());
NewFile.Close();
}
finally
{
//if (doc != null)
//{
doc.close();
// Console.WriteLine("\n\n File saveed - ({0} ", txtOutput);
//}
}
}
}
static void Main(string[] args)
{
args[0] = #"C:\SSIS_Packages\PDF_Import\PDF_Import\PO_pdfs"; //// TESTING FILE PATH1
FilePath(args[0]);
}
}
}
Kind Regards
Rob
I have managed to get it working, I need to enter an argument within the debug screen, see information in URL below
Console app arguments, how arguments are passed to Main method
THank you for everyone's comments

Run forms Application through command prompt and send commands to it

I have a windows forms tool in VB that i have been working on for a while now.
Now i would like to be able to access all of the controls and return values through the command prompt so that i am able to play with it through Azure and basically make the application a black box.
So this is how i went about thinking i should do it.
1 - In my project, i created a second solution, a C# Windows Command line framework.
2 - i than added the following script to that second project in order to run the win forms
using EnabledTest;
using System;
using System.Windows.Forms;
namespace Command_lineStartup
{
internal class Program
{
private static frmMain MainForm;
[STAThread]
private static void Main(string[] args)
{
if (args.Length > 0)
{
// Command line given, display console
}
else
{
AllocConsole();
ConsoleMain(args);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(MainForm = new frmMain());
GUI();
}
}
private static void ConsoleMain(string[] args)
{
Console.WriteLine("Command line = {0}", Environment.CommandLine);
for (int ix = 0; ix < args.Length; ++ix)
Console.WriteLine("Argument{0} = {1}", ix + 1, args[ix]);
// Console.ReadLine();
}
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
public static void GUI()
{
Console.WriteLine("Testing version 1 :");
Console.WriteLine("Enter Project File path to open, Project must be a .mmp file");
string Path = Console.ReadLine();
MainForm.LoadProject(Path);
}
}
}
However, I do not think this is the right way. When i run the console application through CMD using C:\TFS\Enabled Test\Command-lineStartup\bin\Debug\Command-lineStartup.exe"
I does not behave how i want it to work.
So my question is.
Am i going about this the right way? if so what am i doing wrong here
is there an easier way?
So i found a way in the end. When running the application through CMD, the arguments that are supplied can be accessed using
Dim cla As String() = Environment.GetCommandLineArgs()
then for each of the arguments provided u can do something with it.
For example,
If cla.Length > 1 Then
'cla(0) is the executable path.
'cla(1) is the Path to the project
If Not IsIDE() Then WCLicenseIsLicensed("Application", True)
Me.Text = Application.ProductName
mblnLoaded = True
LoadProject(cla(1))
TreeVieuwSystem.Nodes(cla(2)).Expand()
TreeVieuwSystem.SelectedNode = TreeVieuwSystem.Nodes(cla(2)).Nodes.Find(cla(2) & "\" & cla(3), True).First
NodeSelected()
If cla(2) = "Test Plans" Then
TheWindowThatAllowsYouToEditTheObject.RunTestPlan()
ElseIf cla(2) = "Tests" Then
TheWindowThatAllowsYouToEditTheObject.RunTest(False)
End If
Else

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

Function is not running and creating the text file

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.

Get path+filename of file that was opened with my application

I'm an amateur at c# and I've been unable to locate the answer to this.
Perhaps I am not aware of the correct terms to use.
When a video file is dragged onto my exe application, I would like the application to know that it was launched with a file and be able to know the path and filename of that file. This way, the user does not have to use the file>open menu.
Hope that makes sense.
Thanks
You can check the command line arguments which were used to launch the application.
If your application was started by dropping a file on the .exe file, there will be a single command line argument with the path of the file.
string[] args = System.Environment.GetCommandLineArgs();
if(args.Length == 1)
{
// make sure it is a file and not some other command-line argument
if(System.IO.File.Exists(args[0])
{
string filePath = args[0];
// open file etc.
}
}
As your question title states, you want the path and the file name. You can get the file name using:
System.IO.Path.GetFileName(filePath); // returns file.ext
When you drag a file into a C# application, it will goes as an command-line argument to that application. Like console applications, you can catch it on the Main method on the Program class.
I'll explain it using Windows Forms application.
Open your Program class on the solution. Your program class should look like this.
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
By default, when you create Windows Forms applications, they don't treat command line arguments. You have to make a tiny change on the signature of the Main method, so it can receive arguments:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
Now you can handle file name argument passed to the application. By default, Windows will put the file name as the first argument. Just do something like this:
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Before Application.Run method, treat the argument passed.
// I created an overload of the constructor of my Form1, so
// it can receive the File Name and load the file on some TextBox.
string fileName = null;
if (args != null && args.Length > 0)
fileName = args[0];
Application.Run(new Form1(fileName));
}
In case you want to know the constructor overload of my Form1, here it is. Hope it helps!
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Form1(string fileName) : this()
{
if (fileName == null)
return;
if (!File.Exists(fileName))
{
MessageBox.Show("Invalid file name.");
return;
}
textBox1.Text = File.ReadAllText(fileName);
}
}
You need your application's command-line arguments. When you drop a file on your application in Explorer, Explorer opens the application with the file you dropped on it. You can select as many files as you want, drop them on your application and using this line of code, files will be an array of those command line arguments.
string[] files = Environment.GetCommandLineArgs();

Categories

Resources