简体   繁体   中英

How do I properly extract a string from the clipboard

So i'm trying to get the links from the clipboard, I manage to work it out just fine if I have one but I changed my method a bit because let's say I have more than 1 link saved in my clipboard. I get this error

Cannot convert type 'char' to 'string'

I dont see why, everything returns a string or a bool. What is causing this error and how do I resolve it?

if (Clipboard.ContainsText(TextDataFormat.Text))
{
    string clipboardText = Clipboard.GetText(TextDataFormat.Text);
    foreach (string link in clipboardText)
    {
        if (Uri.TryCreate(link, UriKind.Absolute, out var uri))
        {
            rtbLinks.AppendText(uri + "\n");
        }
    }
}

A foreach-loop loops through a collection or an array. In your case, you are using the string as the collection/array. That is somewhat possible; imagine a string as an array of type char.

You could use

foreach (char link in clipboardText)
{
    if (Uri.TryCreate(link, UriKind.Absolute, out var uri))
    {
        rtbLinks.AppendText(uri + "\n");
    }
}

That would only loop through each character of the string, though, and would not really solve your problem.

Have a look at this for more information on the foreach-loop.

What you really need is an array of type string, where you store the links. I imagine you have those strings split by a delimiter (like "|") in your clipboard, so you could modify your code like this:

if (Clipboard.ContainsText(TextDataFormat.Text)) {
    string[] clipboardText = Clipboard.GetText(TextDataFormat.Text).Split('|');
    foreach (string link in clipboardText) {
        if (Uri.TryCreate(link, UriKind.Absolute, out var uri)) {
            rtbLinks.AppendText(uri + "\n");
        }
    }
}

If you have, eg "https://softwareengineering.stackexchange.com|https://stackoverflow.com" in your clipboard, it will split the links into the array of string and you can work with those.

Without a delimiter, things might get a bit more tricky. You would then have to manually split those links into the string array first, and loop through that array afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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