c# - 以用户身份复制和粘贴文件
问题描述
在我的应用程序中有一些文件。我希望能够在应用程序的其他地方复制和粘贴。
我要复制和粘贴的文件已存储在函数中GetPartialExportString()
我的想法:
- 当用户单击“复制”时,我在 comp 的某处创建一个文件并将其存储在新创建的文件中
- 当用户单击“粘贴”时,我从单击复制时生成的文件中读取并将其添加到那里。
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");
}
它不是这样工作的。对此新手,如果有人可以提供帮助,我将不胜感激!
文件路径目前不正确。但即使它们是正常的,它也不起作用!
解决方案
您应该避免覆盖/对象的类的
Close()
方法。改为使用。Stream
MemoryStream
FileStream
Dispose()
您应该先让流对象完成所有工作,然后再处理它们。
readingStream
将object的内容复制到 后file
,您必须将流缓冲区的位置重新调整到readingStream
object 中存在的内容的开头,以便将其成功复制到destinationStream
.
像这样修改您的代码片段:
readingStream.WriteTo(file);
readingStream.Position = 0;
readingStream.CopyTo(destinationStream);
file.Dispose();
readingStream.Dispose();
File.WriteAllText(destFile, modelAsString);
推荐阅读
- javascript - 多次调用的函数反应原生
- python - 如何访问外部数据帧中的数据以带回主数据帧 Pandas
- asp.net-mvc-4 - 关于为什么模板/小部件不会在开发站点上更新的任何想法?它适用于我的本地机器
- r - 如何在ggplot R的facetwrap中创建带有自定义标签的辅助轴
- java - JFrame 上的 MouseListener 永远不会被调用
- latex - 乳胶对齐语法
- firebase - 即使我取消链接,电话仍然有价值(firebase)
- pyspark - Pyspark:过滤数据帧并将函数应用于偏移时间
- javascript - 将 Bootstrap JavaScript 添加到 Docusaurus 但有问题
- mysql - MySQL-如何在子查询中获取动态表名