【问题标题】:Vnext Argument 1: cannot convert from 'string' to 'System.IO.Stream'Vnext 参数 1:无法从 'string' 转换为 'System.IO.Stream'
【发布时间】:2015-02-28 09:19:48
【问题描述】:

我正在尝试使用 Vnext 项目创建一个通用序列化程序,当我调用 StreamWriter 的构造函数时,它会引发此编译器错误

错误 CS1503 参数 1:无法从“字符串”转换为 'System.IO.Stream' Test.ASP.NET Core 5.0 Helper.cs 14

即使有一个构造函数允许指定文件路径作为参数。

这是我的类文件

using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace Test
{
    public static class Helper
    {
        public static void SerializeToXml<T>(string path, T value)
        {
            var serializer = new XmlSerializer(typeof(T));
            using (var stream = new StreamWriter(path)) // ERROR OCCURS HERE
            {
                using (var writer = XmlWriter.Create(stream))
                {
                    serializer.Serialize(writer, value);
                }
            }
        }
    }
}

这是我的 project.json 文件

{
    "version": "1.0.0-*",
    "dependencies": {
    },
    "commands": {
        "run": "run"
    },
    "frameworks": {
        "aspnet50": {
            "dependencies": {

            },
            "frameworkAssemblies": {
                "System.Xml": "4.0.0.0"

            }
        },
        "aspnetcore50": {
            "dependencies": {
                "System.Console": "4.0.0-beta-22231",
                "System.Xml.XmlSerializer": "4.0.0-beta-22231",
                "System.Collections": "4.0.10-beta-22422",
                "System.Xml.ReaderWriter": "4.0.10-beta-22231",
                "System.IO": "4.0.10-beta-22231"
            }
        }
    }
}

【问题讨论】:

  • 它是否适用于非测试版代码?
  • new StreamWriter(path, encoding) 重载 is supported by the portable class libraries 而只有路径的版本不是。你能用那个吗?
  • @SteveWellens 如果我使用普通(非 vnext)控制台项目运行相同的代码,它将起作用。我不确定这是否是您的意思。谢谢您的评论。
  • @dbc 我试过使用 new StreamWriter(path, encoding) 但我仍然遇到同样的错误,真的很奇怪。感谢您的评论。

标签: c# asp.net asp.net-core


【解决方案1】:

这是来自davidfowl的答案

那是因为它在 CoreCLR 上不可用。使用新的 StringWriter(File.OpenWrite(path)) 代替

为了将来参考,我可以在哪里检查某个功能是否可用?

https://github.com/dotnet/corefx 存储库中的文件问题。他们 将能够澄清为什么新框架中缺少一些东西。一世 相信这个特殊的过载被删除的原因是因为 新包之间的分层问题。

不应直接包含 StreamWriter 的程序集 引用文件流:

new StreamReader(path)

确实如此

new StreamReader(new FileStream(path, options)).

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    相关资源
    最近更新 更多