C#File.Read错误:文件已被其他进程使用

时间:2017-06-14 07:25:33

标签: c# file streamreader

我正在尝试解析几个文件,同时这样做有一些值可以忽略等等。我目前使用此代码执行此操作:

public class Test {
    public static void main(String[] args) {
        Question question = new Question();
        JSONArray array = new JSONArray();
        question.setQuestionId("1");
        question.setQuestionText("hello");
        Options option1 = new Options();
        option1.setOption1("1");
        option1.setAnswer("0");
        Options option2 = new Options();
        option2.setOption1("2");
        option2.setAnswer("0");
        Options option3 = new Options();
        option3.setOption1("3");
        option3.setAnswer("0");
        Options option4 = new Options();
        option4.setOption1("4");
        option4.setAnswer("1");     
        List<Options> options = new ArrayList<Options>();
        options.add(option1);
        options.add(option2);
        options.add(option3);
        options.add(option4);
        question.setOptions(options);
        Question newQuestion = null;
        try {
             newQuestion =(Question) question.clone();
        } catch (CloneNotSupportedException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        List<Question> questions = new ArrayList<Question>();
        questions.add(question);
        questions.add(newQuestion);
        for(Question ques: questions){
            JSONObject obj = new JSONObject();
            try {
                obj.put("question", ques.getQuestionText());
            } catch (JSONException e1) {                
                e1.printStackTrace();
            }           
            int i =0;
            for (Options op : ques.getOptions())
            {               
                String arr[] = new String[4];
                arr[0]="option1";arr[1]="option2";arr[2]="option3";arr[3]="option4";                
                try {
                    obj.put(arr[i], op.getOption1());
                    i++;                    
                } catch (JSONException e) {                 
                    e.printStackTrace();
                }               

            }
            array.put(obj);
        }
        System.out.println(array);
    }
}

但我最近得到了错误。在互联网上搜索后我发现了

double[][] rows = File  
         .ReadLines(filepath)  
         .Select(line => line
            .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)  
            .Where(item => !string.Equals("NAN", item, StringComparison.OrdinalIgnoreCase)))   
         .Where(items => items.Any())
         .Select(items => items
           .Select(item => double.Parse(item, CultureInfo.InvariantCulture))  
           .ToArray())
         .ToArray();

会解决这个问题。但是我无法将代码更改为我的需求。当我尝试:

 using (FileStream stream = File.Open("path to file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                while (!reader.EndOfStream)
                { DO SOMETHING}
            }
        }

它给了我一个关于“.Split”的错误,因为它不是StreamReader的已知定义......我知道这可能是一个非常愚蠢的问题并且很容易解决但是我无法管理它做一些如何...

先谢谢

此致

3 个答案:

答案 0 :(得分:1)

Reader.ReadLine()将返回一个字符串。因此,当您对此进行.Select时,您会将其投射到IEnumerable<char>。然后,您无法对char进行.Split

您需要通过一次读取一行来重新格式化代码

所以有一点是这样的:

reader.ReadLine()
      .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
      .Where(item => !string.Equals("NAN", item, StringComparison.OrdinalIgnoreCase))
      .Where(items => items.Any())
      .Select(items => items.Select(item => double.Parse(item.ToString())).ToArray()).ToArray();

<强>更新

要回答您的评论,我很可能会将数据结构从double[][]更改为List<List<double>>

如果你想保留double[][],你可以做这样的事情。

您可以在流式传输文件时更改要添加到列表中的代码:

List<double[]> example = new List<double[]>();

while (!reader.EndOfStream)
{
    example.Add(reader.ReadLine()
      .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
      .Where(item => !string.Equals("NAN", item, StringComparison.OrdinalIgnoreCase))
      .Where(items => items.Any())
      .Select(item => double.Parse(item.ToString(), CultureInfo.InvariantCulture)).ToArray());
}


var returnvalue = example.ToArray();

注意

进行此类更改时,请确保结果与原始代码匹配。

答案 1 :(得分:0)

您需要将reader.ReadLine()替换为reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None)。您也可以为读者类编写自己的扩展方法ReadLines

答案 2 :(得分:0)

使用外部“使用”是否必要?试试这个:

    try
    {
        using (var reader = new StreamReader(filename))
        {
            while (!reader.EndOfStream)
            {
                { your split implementation }
            }
        }
    }

    // now you dont need to close a stream because
    // using statement will handle it for you

    catch // appropriate exception handling
    {

    }