Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法隐式转换类型<;字符串>;串_C#_Uwp_Windows 10 Iot Core - Fatal编程技术网

C# 无法隐式转换类型<;字符串>;串

C# 无法隐式转换类型<;字符串>;串,c#,uwp,windows-10-iot-core,C#,Uwp,Windows 10 Iot Core,我试图为Windows物联网核心构建一个twitter机器人。 我想从名为tweets.csv的文件中获取tweets。 第一步是从文件中获取随机行。 这就是我所尝试的: private String TweetString(int Size = 140) { string[] lines = File.ReadLines(@"C:\Path\tweets.csv"); //Error here System.Text.String

我试图为Windows物联网核心构建一个twitter机器人。
我想从名为tweets.csv的文件中获取tweets。
第一步是从文件中获取随机行。 这就是我所尝试的:

         private String TweetString(int Size = 140)
     {
         string[] lines = File.ReadLines(@"C:\Path\tweets.csv"); //Error here
         System.Text.StringBuilder builder = new System.Text.StringBuilder();
         var r = new Random();
         int randomLine = r.Next(0, lines.Length);
         string line = lines.Skip(randomLine - 1).Take(1).First();
         return builder.ToString();
     }
不幸的是,我得到了这个错误:

无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“string[]”。存在显式转换(是否缺少强制转换?)

有人知道如何解决这个问题吗

(对不起,英语不是我的母语!)

使用LINQ:

确保你有

using System.Linq;
并使用
.ToArray()


您必须将其转换为数组


string[]test=File.ReadLines(@“C:\Path\tweets.csv”).ToArray()

使用
File.ReadAllLines()
读取所有行并将其指定为
string[]

如果您实际上没有将变量用作数组,您只需使用
var
关键字并将方法更新为

Random random = new Random();
private String TweetString(int Size = 140) {
    var lines = File.ReadLines(@"C:\Path\tweets.csv"); //Note *var*
    var builder = new System.Text.StringBuilder();         
    int randomLine = random.Next(0, lines.Length);
    string line = lines.Skip(randomLine - 1).Take(1).First();
    builder.AppendLine(line);//Add the line to the builder.
    return builder.ToString();
}

ReadLines返回IEnumerable而不是字符串数组。您需要具体化IEnumerable以获得数组。只需在File.ReadLines的末尾添加ToArray(),将其转换为数组。string[]test=File.ReadLines(@“C:\Path\tweets.csv”)。ToArray()顺便说一下,行是一个数组。要获取数组的元素,不需要所有Linq代码。只需行[randomLine]最后返回一个空字符串。StringBuilder从未从everything文件初始化为任何东西。ReadLines(@“C:\Path\tweets.csv”)“在UWP中没有什么好处。
Random random = new Random();
private String TweetString(int Size = 140) {
    var lines = File.ReadLines(@"C:\Path\tweets.csv"); //Note *var*
    var builder = new System.Text.StringBuilder();         
    int randomLine = random.Next(0, lines.Length);
    string line = lines.Skip(randomLine - 1).Take(1).First();
    builder.AppendLine(line);//Add the line to the builder.
    return builder.ToString();
}