marceltje
marceltje

Reputation: 127

How to get content of a text file and copy it to clipboard?

I'm creating an application where a user would fill in a bit of code (for example a SteamID), and whenever the user clicks the button, it will be copied to the clipboard.

The way it works is simple, the first time the program runs, and it detects both .txt's in the install dir are empty, the user will be prompted to fill that in.

Everything works until here.

Whenever the user clicks the button, I need a way of the program getting all text in the .txt file, and putting this in the users clipboard.

I've tried literally every method here, but it did not work, or I did not understand it as the code I found would only put text in clipboard that has been programmed into the code, and not that was put into a file.

Upvotes: 4

Views: 4771

Answers (2)

Ankit Vijay
Ankit Vijay

Reputation: 4118

If I understand your question correctly, you are looking to read the content of a text file and then copy it to clipboard

Read from file:

var fileContent= string.Empty;
using (var streamReader = new StreamReader(filePath, Encoding.UTF8)) {            
    fileContent= streamReader.ReadToEnd();
}

OR

var fileContent= File.ReadAllText(filePath);

Copy to clipboard:

Clipboard.SetText(fileContent)

Use namespace System.Windows.Forms for Windows Form or System.Windows for WPF

Upvotes: 0

Hamid Pourjam
Hamid Pourjam

Reputation: 20764

You need a reference to System.Windows or System.Windows.Forms

var content = File.ReadAllText("filepath.txt");
Clipboard.SetText(content);

Upvotes: 3

Related Questions