使用Path对象判断路径的完整性和正确性
using System;
using System.IO; class Test
{ public static void Main()
{
string path1 = @"c:\temp\MyTest.txt";
string path2 = @"c:\temp\MyTest";
string path3 = @"temp"; if (Path.HasExtension(path1))
{
Console.WriteLine("{0} has an extension.", path1);
} if (!Path.HasExtension(path2))
{
Console.WriteLine("{0} has no extension.", path2);
} if (!Path.IsPathRooted(path3))
{
Console.WriteLine("The string {0} contains no root information.", path3);
} Console.WriteLine("The full path of {0} is {1}.", path3, Path.GetFullPath(path3));
Console.WriteLine("{0} is the location for temporary files.", Path.GetTempPath());
Console.WriteLine("{0} is a file available for use.", Path.GetTempFileName()); /* This code produces output similar to the following:
* c:\temp\MyTest.txt has an extension.
* c:\temp\MyTest has no extension.
* The string temp contains no root information.
* The full path of temp is D:\Documents and Settings\cliffc\My Documents\Visual Studio 2005\Projects\ConsoleApplication2\ConsoleApplication2\bin\Debug\temp.
* D:\Documents and Settings\cliffc\Local Settings\Temp\8\ is the location for temporary files.
* D:\Documents and Settings\cliffc\Local Settings\Temp\8\tmp3D.tmp is a file available for use.
*/
}
}
使用FileInfo创建文件
using System;
using System.IO; class Test
{ public static void Main()
{
//通过Path对象获取缓存路径
string path = Path.GetTempFileName();
FileInfo fi1 = new FileInfo(path); //创建文件,并且通过返回的"文件流写入对象"写入数据
using (StreamWriter sw = fi1.CreateText())
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
} //打开文件,并且通过返回的"文件流读取对象"读取数据
using (StreamReader sr = fi1.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
} try
{
string path2 = Path.GetTempFileName();
FileInfo fi2 = new FileInfo(path2); //删除文件
fi2.Delete(); //将f1文件拷贝到f2文件
fi1.CopyTo(path2);
Console.WriteLine("{0} was copied to {1}.", path, path2); //删除文件
fi2.Delete();
Console.WriteLine("{0} was successfully deleted.", path2); }
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}