Get, alter and update the copy cache - c#

I searched pretty much everywhere on google, but I didn't find anything useable. I want to know how to get the current cache and save it on a string. This string will get processed and afterwards replace the current cache.
I am talking about our ordinary copy cache (CTRL + C) on Windows.

Use the System.Windows.Forms.Clipboard.GetText()
http://msdn.microsoft.com/en-us/library/kz40084e.aspx
Example from MSDN:
// Demonstrates SetText, ContainsText, and GetText.
public String SwapClipboardHtmlText(String replacementHtmlText)
{
String returnHtmlText = null;
if (Clipboard.ContainsText(TextDataFormat.Html))
{
returnHtmlText = Clipboard.GetText(TextDataFormat.Html);
Clipboard.SetText(replacementHtmlText, TextDataFormat.Html);
}
return returnHtmlText;
}

First in your console application add reference to System.Windows.Forms.dll via the Solution Explorer window. Then you should be able to add using System.Windows.Forms.
Here is some sample code to read clipboard text from your console application (important : you need the [STAThread] attribute added to your Main as shown below; else there will be a ThreadStateException thrown)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SampleConsole
{
class Program
{
[STAThread]
static void Main(string[] args)
{
if (Clipboard.ContainsText(TextDataFormat.Text))
{
string clipBoardText = Clipboard.GetText(TextDataFormat.Text);
Console.WriteLine("TEXT in ClipBoard : " + clipBoardText);
Console.WriteLine("Type text to replace (and press Enter key) :");
string replaceText = Console.ReadLine();
Clipboard.SetText(replaceText);
Console.WriteLine("REPLACED ClipBoard Text : " + Clipboard.GetText(TextDataFormat.Text));
}
else
{
Console.WriteLine("No text in clipboard, please type now (and press Enter key) :");
string newText = Console.ReadLine();
Clipboard.SetText(newText);
Console.WriteLine("NEW ClipBoard Text : " + Clipboard.GetText(TextDataFormat.Text));
}
Console.Read();
}
}
}

Related

general error handling message for different projects template

I have the following class which writes new line to a text file.
using System;
using System.Text;
using System.IO;
namespace TextStreamer
{
class TextWriter
{
private string _FilePath;
private string _TextToAdd;
// Constructor will assign file Path variable and check if file is valid
public TextWriter(string filePath)
{
this._FilePath = filePath;
ValidateFile();
}
// Validate if the text file exist
private void ValidateFile()
{
// If file does not exist show error message
// and create new text file
if(!File.Exists(_FilePath))
{
Console.WriteLine("File not found");
File.Create(_FilePath);
Console.WriteLine("Created new file {0}", _FilePath);
}
}
// Write new line to the text file
public void WriteNewLine(string text)
{
this._TextToAdd = text + Environment.NewLine;
File.AppendAllText(_FilePath, _TextToAdd);
}
}
}
Right now if the file does not exist it will write a message to the console and then it will create the text file, but what if i used say WPF application, in this case i prefer showing a message box with the same message, how can i achieve that.
I tried throwing exception FileNotFoundException but that just crashes the program and exit.
A simple way to achieve this is by using a public variable to change the option to console log or show message.
Add the namespace for the generic message box:
using System.Windows;
And add a public variable in your class that will let you programmatically change the logging method, such as:
public bool UseMsgBox = false;
You could improve this by using things like using an int or enum to have more logging methods, though a bool is fine for only 2 options.
Add a logging method such as:
private void LogMsg(string msg)
{
if(UseNsgBox) MessageBox.Show(msg);
else Console.WriteLine(msg);
}
And replace your Console.WriteLine's with LogMsg instead.
Make sure to change the option when you create your class:
TextWriter textWriter = new TextWriter("SomeFile.txt");
textWriter.UseMsgBox = true; // or false
Actually, this might not work as you instantly call the LogMsg when your class is created, so perhaps add it as an initialization parameter as well:
public TextWriter(string filePath, bool useMsgBox = false)
{
UseMsgBox = useMsgBox;
// ...
}

Deleting an specified string by user in an array?

What i want to do here was getting an string input from the user and if that string input is in the array i want to delete it from the file (all the items in the array is actual files in my computer that got scanned at the start of the program and become one array) is there a way to do that without foreach?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Threading;
string typed = null;
string loc = AppDomain.CurrentDomain.BaseDirectory;
if (!Directory.Exists(loc + #"\shortcuts"))
{
Directory.CreateDirectory(loc + #"\shortcuts");
}
string[] directory = Directory.GetFiles(loc + #"\shortcuts");
foreach (var filed in directory)
{
File.Move(filed, filed.ToLowerInvariant());
}
string[] file = Directory.GetFiles(loc + #"\shortcuts").Select(System.IO.Path.GetFileNameWithoutExtension).ToArray();
foreach (string dir in directory)
{
}
if (typed == "exit") System.Environment.Exit(0);
//other ifs here
else if (typed == "rem")
{
//Console.WriteLine("\nNot available at the moment\n");
////add this command
Console.WriteLine("\nWhich program entry do you wish to erase?\n");
typed = Console.ReadLine().ToLower();
if (file.Any(typed.Contains))
{
File.Delete(file.Contains(typed)); //this is the broken part and i don't know how i can get the stings from there
Console.WriteLine("hi");
}
else Console.WriteLine("\n" + typed + " is not in your registered programs list.\n");
}
Expected result was getting rid of the typed program in the folder and actual results was just an error code.
You are storing only the file name in the array, not its complete path or extension. You need to change this, and allow it to store FileName with extension.
string[] file = Directory.GetFiles(loc + #"\shortcuts").Select(System.IO.Path.GetFileName).ToArray();
and then, you need to change the If condition as follows.
if (file.Contains(typed))
{
File.Delete(Path.Combine(loc + #"\shortcuts",typed));
Console.WriteLine("hi");
}
In this Scenario, user would need to input the file name with extension.
If you want the User to input only the filename(without extension, as in your code), then, you could run into a situation where there could be two files with different extension.
"test.jpg"
"test.bmp"
Update
Based on your comment that you cannot store extensions, please find the updated code below. In this scenario, you do not need to change the array. Since you are only storing lnk files, you can append the extension to the file name to complete the path during Path.Combine.
if (file.Contains(typed))
{
File.Delete(Path.Combine(loc , #"shortcuts",$"{typed}.lnk"));
Console.WriteLine("hi");
}

To do searching in an array with some keyword

I have an array which is like
books={'java 350','Photoshop 225','php 210','JavaScript 80','python 180','jquery 250'}
my input for search as be like "ph2" it retrieve both Photoshop 225,php 210 in drop-down menu what is the exact string function to do this task or any set codes available to do this task.
I'm using some build in function like
if (array.Any(keyword.Contains))
and
if (array.Contains(keyword))
it's doesn't help what exactly i want any one pls help me to solve this thanks in advance.....
More flexible approach:
using Microsoft.VisualBasic; // add reference
using Microsoft.VisualBasic.CompilerServices;
using System.Linq;
namespace ConsoleApplication
{
class Program
{
static void Main (string[] args)
{
string[] books = { "java 350", "Photoshop 225", "php 210", "JavaScript 80", "python 180", "jquery 250" };
string input = "*" + string.Join ("*", "ph2".ToArray ()) + "*"; // will be *p*h*2*
var matches = books.Where (x => LikeOperator.LikeString (x, input, CompareMethod.Text));
}
}
}

Copying files, skipping alert window 'are you sure message'

My C# console program copies 2 folders into 1. It works but I am new to C#. I cant figure out how I make the program skip the alert window "are you sure you want to overwrite the files".
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic.FileIO;
using System.Diagnostics;
namespace MirrorSystem {
class Program {
static void Main(string[] args)
{
string source1 = #"folder1";
string source2 = #"folder2";
string destination = #"destination";
try
{
Console.WriteLine("Starting..");
FileSystem.CopyDirectory(source1, destination, UIOption.AllDialogs);
FileSystem.CopyDirectory(source2, destination, UIOption.AllDialogs);
Console.WriteLine("Success!");
System.Threading.Thread.Sleep(5000);
Environment.Exit(0);
Console.ReadKey();
}
catch (OperationCanceledException)
{
Console.WriteLine("Canceled!");
Console.ReadKey();
}
}
}
}
You can pass the value true as the third (overwrite) parameter. Here is the official documentation for the method:
public static void CopyDirectory(
string sourceDirectoryName,
string destinationDirectoryName,
bool overwrite
)
The description of the overwrite parameter:
overwrite
Type: System.Boolean
True to overwrite existing files;
otherwise False. Default is False.
Source.
You can use method File.Copy --> https://msdn.microsoft.com/es-es/library/9706cfs5(v=vs.110).aspx
The third parameter allows you to specify whether you should or should not overwrite existing files with the same name in the destination folder.

Windows 7 clipboard copy paste operation using C#

I'm working on a Windows application where I need to use clipboard data. I am trying to copy text from clipboard by the code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace MultiValuedClipBoard
{
class Class1
{
public String SwapClipboardHtmlText(String replacementHtmlText)
{
String returnHtmlText = "hello";
if (Clipboard.ContainsText(TextDataFormat.Html))
{
returnHtmlText = Clipboard.GetText(TextDataFormat.Html);
Clipboard.SetText(replacementHtmlText, TextDataFormat.Html);
}
return returnHtmlText;
}
}
}
Calling the above function by:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Media;
namespace MultiValuedClipBoard
{
class Program
{
static void Main(string[] args)
{
Class1 aas = new Class1();
string a = aas.SwapClipboardHtmlText("chetan");
Console.WriteLine(a);
Console.ReadLine();
}
}
}
When running this code it gives the output "Hello" which is the default value, not clipboard data.
Your code will not work because of two reasons:
[1] When you say:
if (Clipboard.ContainsText(TextDataFormat.Html))
Here you are basically assuming that the clipboard already contains a text and that too in HTML format, but depending on the values you are setting in the clipboard it doesn't look like you are intending to use the pre-existing clipboard value anywhere in your program. So, this if condition should not be there.
[2] Secondly, you are further trying to set the string "chetan" to the clipboard which is definitely not in HTML format. So,
Clipboard.SetText(replacementHtmlText, TextDataFormat.Html);
becomes
Clipboard.SetText(replacementHtmlText, TextDataFormat.Text);
Hence, effectively, your new code becomes something like this:
String returnHtmlText = "hello";
//if (Clipboard.ContainsText(TextDataFormat.Html))
//{
returnHtmlText = Clipboard.GetText(TextDataFormat.Text);
Clipboard.SetText(replacementHtmlText, TextDataFormat.Text);
//}
return returnHtmlText;
Clearly Clipboard.ContainsText(TextDataFormat.Html) evaluates to false. Which means that the clipboard in fact does not contain text in the format you specify.
I changed your program to prove the point:
[STAThread]
static void Main(string[] args)
{
Clipboard.SetText("boo yah!", TextDataFormat.Html);
Class1 aas = new Class1();
string a = aas.SwapClipboardHtmlText("chetan");
Console.WriteLine(a);
Console.WriteLine(Clipboard.GetText(TextDataFormat.Html));
Console.ReadLine();
}
Output:
boo yah!
chetan

Categories