Read text file into Clipboard - c#

after along time of searching via google, I decided to poste my problem here.
First: I am total C# Noob. I am using a Macro Recorder from Jitbit and I have no choice to use a different. The Problem is in the Macro Recorder, it is missing some essential things.
Like reading a text file into a variable and paste this variable via Clipboard :-(
However the good thing is, the tool support "some" type of native C# Code
If I open the C# Command I get this:
public class Program
{
public static void Main()
{
System.Windows.Forms.MessageBox.Show("test");
}
}
And the C# program has to follow also these rules:
=> This Code MUST contain a class named "Program" with a static method "Main"
I already used google and found code that should do the job but I get errors, I guess the
code doesn`t follow the above rules.
This is what I found and tried:
using System;
using System.IO;
public class Program
{
public static void Main()
{
// Read the file as one string.
System.IO.StreamReader myFile =
new System.IO.StreamReader("Counter.txt");
string counter = myFile.ReadToEnd();
myFile.Close();
// Load string into clipboard
Clipboard.SetDataObject( counter, true );
}
}
I always get the error : "Line 15: The Name Clipboard is not existing in the context"?!?
I hope that someone can explain a noob (me) what is wrong and what is the correct code.
Thanks.

add reference to System.Windows.Forms
using System;
using System.IO;
using System.Windows.Forms;
public class Program
{
[STAThread]
public static void Main()
{
Clipboard.SetDataObject(File.ReadAllText("Counter.txt"), true);
}
}
Note that to Avoid the ThreadStateException you need to applying the STAThread attribute to your Main() function

Related

Title: C# File.Exist returning false when file can be read from/written to

Development Environment: .Net Framework 4.7.2 using VS 2022 on Win 10 Pro x64
Preface: I've reviewed the two similar questions I found at SO; the first deals with permissions and the second with restrictions on using the root directory. Neither contained info that enabled me to resolve my issue.
I'm working on a C# winforms app which uses a SQLite database. I recently discovered "PRAGMA integrity_check" will create an empty DB and return “ok” if the target DB file is missing so I need to ensure the file’s not gone missing before executing the PRAGMA. My simple solution is to wrap integrity_check in an IF (File.Exist) ELSE but the Exist method is returning ”false”.
In MSDN documentation there 7 stated reasons why a false might be returned in addition to the file actually not existing (listed to avoid the need to follow a link):
path is null
path is invalid
path exceeds maximum length (260)
path is a zero-length string
path has invalid characters
storage media is failing/missing
caller has insufficient permissions to read the specified file
My operating assumption is none of those are the root cause since I can read from and write to the DB programmatically in the app.
Code building the path:
namespace BURS_Library
{
public class MISC
{
public const string DBName = "BURS.db";
}
}
using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
namespace BURS_Library
{
public class BURS_Path
{
public static string AppData()
{
string userAppDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
userAppDataDir = userAppDataDir.Replace("Roaming", "LocalLow");
if ( ! Directory.Exists(Path.Combine(userAppDataDir, "BURS_Data_tst")))
{
// display error MessageBox
Environment.Exit(1);
}
return Path.Combine(userAppDataDir, "BURS_Data_tst");
}
public static string DB()
{
return Path.Combine(AppData(), MISC.DBName);
}
{
}
Resultant path: C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db
Code with File.Exist
using _Library;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace BURS_UI
{
public static class Program
{
[STAThread]
public static void Main(string[] tsArgs)
{
if (File.Exists(BURS_Path.DB()))
{
// perform db Integrity Check
}
else
{
// display error MessageBox
Environment.Exit(2);
}
BURS_Connections.SetConnection(BURS_Path.DB());
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Discover());
}
}
}
If my operating assumption is valid why is File.Exist returning false?
Thank you for your time & expertise.
Following #BentTranberg's suggestion a test was run using the following code (in case its useful to somebody):
if (Directory.Exists(#"C:\Users"))
Save2Log(#"FOUND: C:\Users", true);
if (Directory.Exists(#"C:\Users\Art"))
Save2Log(#"FOUND: C:\Users\Art", true);
if (Directory.Exists(#"C:\Users\Art\AppData"))
Save2Log(#"FOUND: C:\Users\Art\AppData", true);
if (Directory.Exists(#"C:\Users\Art\AppData\LocalLow"))
Save2Log(#"FOUND: C:\Users\Art\AppData\LocalLow", true);
if (Directory.Exists(#"C:\Users\Art\AppData\LocalLow\BURS_Data_tst"))
Save2Log(#"FOUND: C:\Users\Art\AppData\LocalLow\BURS_Data_tst", true);
if (File.Exists(#"C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db"))
Save2Log(#"FOUND: C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db", true);
Save2Log($"METHOD: {BURS_Path.DB()}", true);
Which produced the following result:
FOUND: C:\Users
FOUND: C:\Users\Art
FOUND: C:\Users\Art\AppData
FOUND: C:\Users\Art\AppData\LocalLow
FOUND: C:\Users\Art\AppData\LocalLow\BURS_Data_tst
FOUND: C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db
METHOD: C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db
Next I reran my original code which surprisingly now worked as expected. To validate that result I ran more test:
int existFail = 0;
for (int i = 0; i < 10000; i++)
{
if ( ! File.Exists(BURS_Path.DB())) existFail++;
}
Save2Log($"number of exist fail in 10,000 = {existFail}", true);
I did that 5 times and in 50,000 iterations there were zero incorrect returns. At this point the error has not been reproduced.
My computer was shut down over night which may have impacted the findings. I will rerun this each morning for the next 3 days and post the results as an edit.

Could not find 'Program' specified for Main method [duplicate]

This question already has answers here:
Could not find 'WindowsFormsApplication1.Program' specified for Main method after renaming name space
(3 answers)
Closed 2 years ago.
I have this problem where i have 2 files inside a project. One called Program.cs and another called Book.cs
I tried running the Program.cs but it comes up with the error: "Could not find 'Program' specified for Main method".
Here's the code for Program.cs
using System;
namespace Classes_Objects
{
class Program
{
public static void Main(string[] args)
{
Book book1 = new Book();
book1.title = "Harry Potter";
book1.author = "JK Rowling";
book1.pages = 400;
Console.WriteLine(book1.pages);
Console.ReadLine();
}
}
}
Here's the code for Book.cs
using System.Text;
using System.Threading.Tasks;
namespace Classes_Objects
{
class Book
{
public string title;
public string author;
public int pages;
}
}
Please download .net core SDk after that open VS code, open the folder where you want to execute .cs programs and install C# plugin
after that please try these commands which worked for me
open terminal in VS code and type dotnet new console
it will create Program.cs file , .csproj, obj folder
Create your file Book.cs and implement both of your book code and program code in that folder which should have same namespace name
then run this command dotnet run .\Program.cs
The Output will be :
400
Remember in your code there is Console.ReadLine(); after printing the value.

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

Execute functions of another C# running program

I have a litle program in c#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int count;
static void Main(string[] args)
{
for (int i = 0; i<10; i++)
{
Console.WriteLine(func_count());
Console.ReadKey();
}
}
static int func_count()
{
return count++;
}
}
}
I want to write another simple C# program that will be able JUST to execute the func_count(). The first exe will be allready running, I don't want to execute it inside the second application and reflect it's properties.
In C after getting the right to access the memory region to avoid seg fault I would have to use a pointer to a function - something like:
int (* func_ptr)(); //pointer to function
func_ptr = func_count_address
What's a simple way to do this in C# like above?
Suppose that the first program (the one given) is as is and I can't change the code.
Thank you
Why not simply call the static method: ConsoleApplication1.Program.func_count(). This of course assumes that you reference the assembly where ConsoleApplication is located within your second app and that the method you want to invoke is public (which is currently is NOT).
EDIT: If you may not change the access-modifier of the desired method you may use reflection to invoke it however.
Sth. like this:
MethodInfo m = typeof(ConsoleApplication.Program).GetMethod("func_count", BindingFlags.NonPublic);
object result = m.Invoke(null, yourParams);
Usually you´d need an instance on which that method is executed. Since your method is static it does not need it and therefor the first param to Invoke is NULL.

Getting and using current directory in c# script

This is just a sample, but it will help illustrate what I'm trying to do.
I know how to get the current directory as shown in the script below, and I can can set a file variable.
The problem I'm having is that I can't figure out how to make it create a folder and put the file in the folder
For example (using the variables below)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var cd = Directory.GetCurrentDirectory();
Directory.CreateDirectory(cd: \5app\);
File.Copy(c:\xyz.txt, cd: \5app\xyz.txt
}
}
}
I know what I have written above is not correct because vs10 tells me so, but doesn't give me very much help.
You're missing a parenthesis and a semicolon, and, especially, arguments of methods Directory.CreateDirectory() and File.Copy() are strings, put them inside quotes:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var cd = Directory.GetCurrentDirectory();
Directory.CreateDirectory(cd + #"\5app\");
File.Copy(#"c:\xyz.txt", cd + #"\5app\xyz.txt");
}
}
}
MSDN references: Directory.CreateDirectory, File.Copy
Thanks to Cole Johnson for pointing out that it shouldn't be #"cd: \5app\".
You don't use quotes.
In addition, I recommend against explicit parameter naming. If you look at the CIL generated when using explicit parameters, there is a performance downgrade as the parameter variables are saved to a local variable, then passed. This results in an unneeded strfld command.
There are several problems with your code, which Compiler Errors will likely help you to unravel:
The method Directory.CreateDirectory(string path) requires a string, which is encased in "".
Here is an MSDN article on how to use Directory.CreateDirectory
Same with the method File.Copy(string source, string destination)
Here is an MSDN article on how to use File.Copy
Since Directory.GetDirectory() returns a string, you can just concatinate your specific directory to the result. But remember to use proper Escape Sequences in your strings for things like Backslash.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string cd = Directory.GetCurrentDirectory();
Directory.CreateDirectory(cd + "\\5app\\");
File.Copy("c:\\xyz.txt", cd + "\\5app\\xyz.txt");
}
}
}

Categories

Resources