C# Invalid FORMATETC structure when using GetTextAsync

134 Views Asked by At

I'm trying to make a progam which automatically searches for the word I copied in a file and then replaces that word in the clipboard with the line on which it was found in my file. I successfully setup an Eventhandler to see when the clipboard changes. I'm now trying to implement a way of reading my file.

After trying to use the StringReader the Exception is thrown:

Invalid FORMATETC structure occurred.

This is my code right now:

public partial class MainWindow : System.Windows.Window
{
    string line;
    string currentClipboardContent;
    string expectedClipboardContent;
    string vocabularygerman = Properties.Resources.vocabularygerman;
    string vocabularyfrench = Properties.Resources.vocabularyfrench;
    int lineNumber;

    public MainWindow()
    {
        InitializeComponent();
        Windows.ApplicationModel.DataTransfer.Clipboard.ContentChanged += new EventHandler<object>(this.TrackClipboardChanges_EventHandler);
    }

    private async void TrackClipboardChanges_EventHandler(object sender, object e)
    {
        DataPackageView dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
        if (dataPackageView.Contains(StandardDataFormats.Text))
        {
            currentClipboardContent = await dataPackageView.GetTextAsync();
            if (expectedClipboardContent != currentClipboardContent)
            {
                Thread.Sleep(500);

                
                using (var reader = new StringReader(vocabularygerman))
                {
                    lineNumber = 0;
                    while ((line = reader.ReadLine()) != null)
                    {
                        lineNumber++;
                        if (line.Contains(currentClipboardContent))
                        {
                            System.Windows.Forms.Clipboard.SetDataObject(lineNumber);
                            break;
                        }
                    }
                }
                expectedClipboardContent = System.Windows.Forms.Clipboard.GetText();
            }
        }
    }

Everything worked fine until I tried to use the StringReader. I'm thinking of ditching the stringreader altogether and using a streamreader, but I am not able to use my vocabularygerman.txt file in my resources.

1

There are 1 best solutions below

1
On BEST ANSWER

StringReader does not implement the IDataObject interface so SetDataObject method wont like that as it depends on that interface being present.

Try

Clipboard.SetText(lineNumber.ToString())

instead if you need the StringReader.

PS: use await for async calls