我在看这段代码是否正确. [英] I am looking to see if this code is right.

查看:83
本文介绍了我在看这段代码是否正确.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建目录
它必须首先检查目录是否存在.如果不创建一个.

I am trying to create a directory
It must first check to see if directory exist. If not create one.

public void createNewFolder()
{
  DirectoryInfo di = new DirectoryInfo("..\\DATA\\" + BUSINESSNAME.Text);

  //Check to see if company directory exist
  if (!di.Exists)
  {
    try
    {
     di = Directory.CreateDirectory(this.Server.MapPath("..\\DATA\\" + BUSINESSNAME.Text));
    }
    catch
    {
     this.Page.Response.Write("Director was not created.");
    }
  }
   else
   {
    this.Page.Response.Write("Director exist already. Please go to edit/update Page.");
   }
}

推荐答案

为什么不调试它,看看它是否正常工作?在当前状态下,它将仅检查一个相对的目录,该目录应位于预定义的DATA目录下.

另一个说明.在我看来,将目录名作为参数传递比将其硬编码到方法中会更好(并且很可能可重用).
Why not debug it and see if it works correctly? At it''s current state it''ll just check one relative directory which should be under predefined DATA directory.

Another note. In my opinion it would be more elegant (and likely to be re-usable) to pass the directory name as a parameter than to hard code it into the method.


我建​​议这样做需要修改.

目前,您正在检查一个文件夹,然后(可能)创建一个具有不同路径的文件夹.相反,尝试构建一个新字符串,并独家使用它:
I would suggest that it needs some revision.

At present, you are checking one folder, then (potentially) creating one with a different path. Instead, try building a new string, and using that exclusivly:
string path = Server.MapPath(@"..\DATA\" + BUSINESSNAME.Text);



其次,为什么不使用与您检查过的相同的DirectoryInfo?



Secondly, why not use the same DirectoryInfo as you checked with anyway?

DirectoryInfo di = new DirectoryInfo(path);
if (!di.Exists)
    {
    try
        {
        di.Create();
        }
    catch (Exception ex)
        {
        ...
        }
    }
else
    {
    ...
    }


检查目录是否存在时,所检查的路径与用于创建新目录的路径相同.

您检查是否存在"..\\DATA\\" + BUSINESSNAME.Text,但随后创建了this.Server.MapPath("..\\DATA\\" + BUSINESSNAME.Text).

DirectoryInfo对象应该使用相同的this.Server.MapPath("..\\DATA\\" + BUSINESSNAME.Text)路径.
When you check to see if your directory exists, you are not checking the same path as the path you are using to create the new directory.

You check to see if "..\\DATA\\" + BUSINESSNAME.Text exists, but then you create this.Server.MapPath("..\\DATA\\" + BUSINESSNAME.Text).

The DirectoryInfo object should probably use the same this.Server.MapPath("..\\DATA\\" + BUSINESSNAME.Text) path.


这篇关于我在看这段代码是否正确.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆