简体   繁体   English

如何获取文本文件的内容并将其复制到剪贴板?

[英]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. 我正在创建一个用户填写一些代码的应用程序(例如SteamID),每当用户单击该按钮时,它将被复制到剪贴板。

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. 它的工作方式很简单,程序第一次运行时,它检测到安装目录中的.txt都是空的,系统会提示用户填写该文件。

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. 每当用户单击该按钮时,我需要一种程序获取.txt文件中的所有文本,并将其放在用户剪贴板中。

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. 我已经尝试过这里的每一个方法,但它没有用,或者我不理解它,因为我发现的代码只会将文本放入已经编入代码的剪贴板中,而不是放入文件中。

You need a reference to System.Windows or System.Windows.Forms 您需要对System.WindowsSystem.Windows.Forms的引用

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

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 使用命名空间System.Windows.Forms for Windows Form或System.Windows for WPF

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM