判断服务器或者硬盘中文件是否存在,并创建文件

文章出自http://dengzebo.blog.163.com/blog/static/1886740620092112561255/

WinForm判断远程Web服务器文件是否存在  

        private bool GetServerFileExists(string URL)
        {
            try
            {
                System.Net.WebRequest s = System.Net.WebRequest.Create(URL);
                s.Timeout = 6000;
                System.Net.WebResponse a = s.GetResponse();
                return true;
            }
            catch
            {
                return false;
            }
        }
 
 
 
方法1: 

C#代码  
if (Directory.Exists("d:\\pic"))   
{   
    MessageBox.Show("存在");   
}   
else  
{   
    MessageBox.Show("不存在");   
}     
方法2: 

C#代码  
DirectoryInfo TheFolder = new DirectoryInfo("d:\\pic");   
if (TheFolder.Exists)   
{   
    MessageBox.Show("进来了");   
}   
else  
{   
    MessageBox.Show("没进来");   
}  
"d:\\pic"可以这样变成路径 
@"d:\pic" 
也就是说转义符可以用@来代替 

新建文件夹: 

C#代码  
if (!Directory.Exists(@txtFileSaveDir.Text))//若文件夹不存在则新建文件夹   
{   
    Directory.CreateDirectory(@txtFileSaveDir.Text); //新建文件夹   
}  

 

1:文件夹是否存在,不存在进行创建

         //给一个默认的文件路径E:\\TestFolderIsExist
            string folderPath = this.txtfolder.Text;
            //文件夹不存在
            try
            {
                //这和asp.net的写法有点不一样
                if (System.IO.Directory.Exists(folderPath) == false)
                {
                    System.IO.Directory.CreateDirectory(folderPath);
                }
                MessageBox.Show("创建成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("创建失败");
                throw ex;
            }

2:判断文件是否存在,如果存在就删除

string filePath = “E:\\TestFileIsExist\\abc.txt”;

 if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                    MessageBox.Show("文件已经删除");
                }
                else
                {
                    MessageBox.Show("文件不存在");    

 

 

                   //接下来 可以进行保存文件的操作了
                }

 

 判断文件存不存在  第一个方法

C#代码 复制代码 收藏代码
  1. File.Exists(Application.StartupPath + "\\AlarmSet.txt")  
File.Exists(Application.StartupPath + "\\AlarmSet.txt")




判断文件存不存在  第二个方法

C#代码 复制代码 收藏代码
  1. System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(Application.StartupPath + "\\AlarmSet.txt");   
  2. MessageBox.Show(info.Exists.ToString());  
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(Application.StartupPath + "\\AlarmSet.txt");
MessageBox.Show(info.Exists.ToString());



创建文件

C#代码 复制代码 收藏代码
    1. File.Create(Application.StartupPath + "\\AlarmSet.txt");//创建该文件
posted @ 2013-03-12 12:00  苏苏zhao  阅读(654)  评论(0编辑  收藏  举报