【问题标题】:How to change the folder where the Enviroment.CurrentDirectory is positioned. C#如何更改 Environment.CurrentDirectory 所在的文件夹。 C#
【发布时间】:2016-09-07 15:03:01
【问题描述】:

我想更改定位文件夹以创建一个可以使用的文件,所有这些都在运行时进行。

是否有任何形式可以动态定位 Release 文件夹以在其中创建文件并使用它?

或者,如果这是不可能的,

是否可以指示移动我在 Enviroment.CurrentDirectory 中找到的文件夹,以便我可以将自己放置在我有权创建文件而没有任何问题的空间中?

就像“C:/”一样,如果这当然可行,我需要把它放在我以后可以修改的地方。

我正在寻找创建一个 json 文件以供使用 这是基本代码:

  public partial class WebForm1 : System.Web.UI.Page
    {
        List<LoginData> lstLoginData = new List<LoginData>();

        //with this one you check if login was successfull
        public bool loginValidated = false;
        string nameFile = "SomeFile.json";
        string WhereIsTheFile = Environment.CurrentDirectory + "\\";

        DataTable dt = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            WhereIsTheFile += nameFile;
            if (!File.Exists(nameFile))
            {
                File.Create(nameFile);
                WhereIsTheFile = Environment.CurrentDirectory + "\\" + nameFile;
                string SomeOtherString = WhereIsTheFile;
            }

            lstLoginData = parsingReadJSONfile(WhereIsTheFile);

            if (IsPostBack)
            {
                lstLoginData = (List<LoginData>)ViewState["listado"];
                if (lstLoginData == null)
                {
                    lstLoginData = new List<LoginData>();
                }
            }

            if ((!string.IsNullOrWhiteSpace(Session["Name"].ToString())) && (!string.IsNullOrWhiteSpace(Session["passwrd"].ToString())))
            {
                //Here happends if login is successfull
                foreach (LoginData usrData in lstLoginData)
                {
                    if (usrData.name == Session["Name"].ToString())
                    {
                        if (usrData.passwrd == Session["passwrd"].ToString())
                        {
                            loginValidated = true;
                        }
                    }
                }
            }

            if (ViewState["data"] == null)
            {
                DataTable dtbl = new DataTable();
                dtbl.Columns.Add("Name");
                dtbl.Columns.Add("passwrd");
                ViewState["data"] = dtbl;
            }

        }

        protected void btnIngresar_Click(object sender, EventArgs e)
        {

        #region Codigo Sin Usar (Comentado)
        //before add value get viestate to dataTable
        //    dt = (DataTable)ViewState["data"];
        //    string _valueName = txbNombre.Text.ToUpper().Trim();
        //    string _valuePassword = txbPassword.Text.Trim();
        //    LoginData newLoginData = new LoginData() { name = _valueName, passwrd = _valuePassword };
        //    dt.Rows.Add(newLoginData);

        //    //Now bind data
        //    ListBox1.DataSource = dt;

        //    ListBox1.DataTextField = "Name";
        //    ListBox1.DataValueField = "name";

        //    ListBox1.DataTextField = "passwrd";
        //    ListBox1.DataValueField = "passwrd";

        //    ListBox1.DataBind();

        //    txbNombre.Text = txbPassword.Text = string.Empty; //To Clear the data
        #endregion

            Session["Name"] = txbNombre.Text.Trim();
            Session["passwrd"] = txbPassword.Text.Trim();
        }

        //Listo registrar
        protected void btnRegistrar_Click(object sender, EventArgs e)
        {
            parsingWriteJSONfile(txbNombre.Text, txbPassword.Text, "SomeFile.json");
        }

        public void parsingWriteJSONfile(string LoginName, string LoginPassword, string NameOfFile)
        {
            List<LoginData> oldLogin = parsingReadJSONfile(NameOfFile);
            List<LoginData> newLogin = new List<LoginData>();

            if ((oldLogin != null) && (oldLogin.Count() >= 1))
            {
                newLogin.AddRange(oldLogin);
            }

            LoginData newLoginData = new LoginData() { name = LoginName, passwrd = LoginPassword };
            newLogin.Add(newLoginData);

            //JavaScriptSerializer ser = new JavaScriptSerializer();
            File.WriteAllText(NameOfFile, JsonConvert.SerializeObject(newLogin));
        }

        public List<LoginData> parsingReadJSONfile(string NameOfFile)
        {
            String JSONstring = File.ReadAllText(NameOfFile);

            //JavaScriptSerializer ser = new JavaScriptSerializer();
            List<LoginData> p1 = new List<LoginData>();
            return p1 = JsonConvert.DeserializeObject<List<LoginData>>(JSONstring);
        }
    }

【问题讨论】:

  • 您将始终可以访问通过 C: 访问的项目文件夹,没有反斜杠

标签: c# json file directory json.net


【解决方案1】:

您根本不需要 Environment.CurrentDirectory,尤其是在 Web 应用程序中。相反,您应该使用 APP_DATA 文件夹并在该文件夹中读取和写入文件。此外,要创建此文件夹的完整路径,您可以使用 Server.MapPath 方法

public partial class WebForm1 : System.Web.UI.Page
{
    List<LoginData> lstLoginData = new List<LoginData>();

    //with this one you check if login was successfull
    public bool loginValidated = false;
    string nameFile = "SomeFile.json";

    // This builds the full qualified filename to your json file and you
    // can use with the standard File.IO methods 
    string WhereIsTheFile = Server.MapPath("~/APP_DATA/" + nameFile);
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!File.Exists(WhereIsTheFile))
        {
            File.Create(WhereIsTheFile);
            ......

        }
        lstLoginData = parsingReadJSONfile(WhereIsTheFile);
        ....

Some info on the APP_DATA folder

【讨论】:

  • 这似乎是一个很好的答案,但你能显示你使用的参考吗?由于某种原因,“服务器”没有与我正在使用的“地图路径”连接。从哪里获得服务器和 MapPath?,您包括哪些参考?提前致谢。
  • Server 静态对象在 System.Web 程序集中定义,要使用它,您需要在文件顶部添加 using System.Web;。这应该默认出现在 WebForms 项目中。完整参考是 HttpContext.Current.Server.MapPath See the example here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多