System.IO.IOException:尝试写入文件时由另一个进程使用的文件

时间:2016-08-31 09:19:14

标签: c# asp.net json

我在互联网上搜索并看到很多关于它的问题,我尝试了许多建议解决方案,但似乎没有什么对我有用(也许我没有正确实施)

这是我的aspx.cs代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;

public partial class Default : Page
{
    static List<Member> memberList = new List<Member>();
    static string fileName = @"C:\Users\Nir - PC\Desktop\public\gradesClient.json";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (File.Exists(fileName))
        {
            using (StreamReader re = new StreamReader(fileName))
            {
                JsonTextReader reader = new JsonTextReader(re);
                JsonSerializer se = new JsonSerializer();
                object parsedData = se.Deserialize(reader);
                string json = JsonConvert.SerializeObject(parsedData);

                Console.Write(json);
            }
        }
    }

    protected void addBtn_Click(object sender, EventArgs e)
    {
        memberList = JsonConvert.DeserializeObject<List<Member>>(File.ReadAllText(fileName));

        Member member = new Member();

        member.id = 4;
        member.name = name.Value;
        member.email = email.Value;
        member.Date = date.Value;
        member.Address = address.Value;
        member.Country = country.Value;
        member.Zip = zip.Value;
        member.Grade = Int32.Parse(grade.Value);
        member.Course = course.Value;

        memberList.Add(member);

        string json = JsonConvert.SerializeObject(memberList.ToArray());
        File.WriteAllText(fileName, json);
    }
}


public class Member
{
    public int id { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public string Date { get; set; }
    public string Address { get; set; }
    public string Country { get; set; }
    public string Zip { get; set; }
    public int Grade { get; set; }
    public string Course { get; set; }

    public Member()
    {

    }
}

当它到达行File.WriteAllText(fileName, json);

时会发生错误

请帮我解决问题, 请提供示例代码。

由于

0 个答案:

没有答案