首页 > 解决方案 > 以用户身份复制和粘贴文件

问题描述

在我的应用程序中有一些文件。我希望能够在应用程序的其他地方复制和粘贴。

我要复制和粘贴的文件已存储在函数中GetPartialExportString()

我的想法:

    MemoryStream destinationStream = new MemoryStream();  
    protected void CopyCommand()
    {
        var modelAsString = GetPartialExportString();
        
        string fileName = "copy.xaml";
        string targetPath = @"C:\Users\";
        string destFile = System.IO.Path.Combine(targetPath, fileName);

        //System.IO.Directory.CreateDirectory(targetPath);

        // convert string to stream
        byte[] byteArray = Encoding.UTF8.GetBytes(modelAsString);
        MemoryStream readingStream = new MemoryStream(byteArray);

        FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write);

        readingStream.WriteTo(file);
        file.Close();
        readingStream.Close();

        readingStream.CopyTo(destinationStream);

        File.WriteAllText(destFile, modelAsString);
    }

    protected void PasteCommand()
    {
            string importString = File.ReadAllText("d:\\temp.txt");
            LoadUnitFromXamlString("d:\\temp.txt");
    }

它不是这样工作的。对此新手,如果有人可以提供帮助,我将不胜感激!

文件路径目前不正确。但即使它们是正常的,它也不起作用!

标签: c#wpf

解决方案


  1. 您应该避免覆盖/对象的类的Close()方法。改为使用。StreamMemoryStreamFileStreamDispose()

  2. 您应该先让流对象完成所有工作,然后再处理它们。

  3. readingStream将object的内容复制到 后file,您必须将流缓冲区的位置重新调整到readingStreamobject 中存在的内容的开头,以便将其成功复制到destinationStream.

像这样修改您的代码片段:

readingStream.WriteTo(file);

readingStream.Position = 0;
readingStream.CopyTo(destinationStream);

file.Dispose();
readingStream.Dispose();

File.WriteAllText(destFile, modelAsString);

推荐阅读