使用csc编译引用System.Net.Http的C#文件报错,求解决方法
嘿,我完全懂你熬一整晚折腾编译的崩溃——Visual Studio里能正常跑的代码,到了命令行用csc就卡壳在System.Net.Http的引用上,这事儿确实容易让人头大。
问题原因
在.NET Framework中,System.Net.Http是一个独立的程序集,csc编译器默认不会自动引用它(而Visual Studio会在项目配置里帮你自动添加这个引用),所以直接跑csc Program.cs就会报CS0234错误。
解决办法
你需要在编译命令里手动添加对System.Net.Http.dll的引用,用/r参数(或者/reference)指定这个程序集:
csc Program.cs /r:System.Net.Http.dll
如果编译器找不到这个dll的路径,你可以指定它的完整路径(VS2017通常对应.NET Framework 4.x,路径类似下面这样,可根据你的系统和框架版本微调):
csc Program.cs /r:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Net.Http.dll
验证你的代码
你的代码里已经正确引用了System.Net.Http命名空间:
using System; using System.IO; using System.Net; using System.Net.Http; using System.Collections; using System.Text.RegularExpressions; namespace SimpleWebCrawlerApp { class Program { internal static int SUCCESS = 0; internal static int FAIL = -1; static void Main(string[] args) { TextWriter errorWriter = Console.Error; if (args.Length != 2) { errorWriter.WriteLine("usage: <program_name>.exe <http/https url> <number of hops>"); } else { if (IsValidUrl(args[0])) { int hops; if (int.TryParse(args[1], out hops)) { new HTTPCrawler(args[0], hops).Crawl(); Environment.Exit(SUCCESS); } errorWriter.WriteLine("not a valid integer for number of hops"); } else { errorWriter.WriteLine("observe proper http/https protocol"); } } Environment.Exit(FAIL); } } }
所以只要加上引用参数,编译应该就能成功了。
附你遇到的错误信息
C:\Users\farao\Documents\Visual Studio 2017\source\repos\SimpleWebCrawlerApp\SimpleWebCrawlerApp>csc Program.cs
Microsoft (R) Visual C# Compiler version 2.6.0.62329 (5429b35d)
Copyright (C) Microsoft Corporation. All rights reserved.Program.cs(4,18): error CS0234: The type or namespace name 'Http' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)
内容的提问来源于stack exchange,提问作者carsomyrxp

