文件的创建、删除、移动和查找

  File.Create方法在制定路径中创建文件。此方法创建的FileStream对象的FileShare默认值为None,直到关闭原始文件句柄后,其他进程或代码才能够访问这个创建的文件。

  如果指定的文件不存在,则创建该文件:如果指定的文件存在并且不是只读,将改写其内容。在指定路径中创建一个文件,将一些信息写入该文件,再从文件中读取。用file.create可以产生文本文件和其他文件,如XML文件。

string path=@"..\..\MyTest.txt";

try

{

  if(File.Exists(path))

    File.Delete(path);

  using(FileStream fs=File.Create(path))

  {

    Byte[]info=new UTF8Encoding(true).GetBytes("This is some text in the file.");

    fs.Write(info,0,info.Length);//添加一些信息到文件

  }

}

catch (Exception Ex)
{
        Console.WriteLine(Ex.ToString());
}

程序运行后在项目文件夹中产生文本文件MyTest.txt,屏幕显示文件内容:

This is some text in the file.

  File.Move方法将指定文件移动到新位置,并提供指定新文件名的选项。File.Delete删除指定的文件。如果指定的文件不存在,则不引发异常

  此方法对整个磁盘卷工作,并且如果源和目标相同,不会引发异常。如果试图通过一个文件一道该目录中替换文件,将发生IOException异常。不能使用Move方法改写现在文件

  下面的示例可以移动和删除一个文件

  string pathSource=@"..\..\pathSource";

  string pathTarget=@"..\..\pathTarget";

//在项目文件夹创建源目录pathSource和目标目录pathTarget

             try
            {
                if (!Directory.Exists(pathSource))
                    Directory.CreateDirectory(pathSource);
                if (!Directory.Exists(pathTarget))
                    Directory.CreateDirectory(pathTarget);
            }
            catch (Exception e)
            {
                Console.WriteLine("The process failed{0}",e.ToString());
            }
            string fileSource = pathSource + @"\MyTest.txt";
            string fileTarget = pathTarget + @"\MyTest.txt";
            try
            {
                if (!File.Exists(fileSource))
                    using (FileStream fs = File.Create(fileSource)) { }
                if (File.Exists(fileTarget))
                    File.Delete(fileTarget);
                File.Move(fileSource, fileTarget);
                Console.WriteLine("{0}was moved to{1}.", fileSource, fileTarget);
                if (File.Exists(fileSource))
                    Console.WriteLine("The orginal file still exists,which is unexpected.");
                else
                    Console.WriteLine("The original file no longer exists,which is expected");
            }
            catch (Exception e)
            {
                Console.WriteLine("The process failed:{0}", e.ToString());
            }
            finally { }

运行结果为:

..\..\pathSource\MyTest.txt was moved to..\..\pathTarget\MyTest.txt

The original file no longer exists,which is expected.

posted on 2014-03-12 16:52  吃鱼的木头  阅读(222)  评论(0编辑  收藏  举报

导航