|
<< Click to Display Table of Contents >> Diretórios e Arquivos |
![]() ![]()
|
Vários exemplos de uso:
Saber se arquivo existe
if (File.Exists("animal0.jpg")) ...
Renomear arquivo
File.Move("animal.txt", "animal.old");
Excluir arquivo
File.Delete("animal.txt");
Listando diretório
DirectoryInfo dirinfo = new DirectoryInfo(@"D:\temp\FreeRapid\lookandfeel");
foreach (FileInfo arquivo in dirinfo.GetFiles())
Console.WriteLine(arquivo.Name + " " + arquivo.Length);
Incluindo uma barra no final do caminho
static string DirBarra(string path)
{
return path.EndsWith(Path.DirectorySeparatorChar.ToString()) ? path : path + Path.DirectorySeparatorChar;
}
Diretório da aplicação
string pasta = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
Apagar um arquivo
File.Delete(@"d:\a.txt");
Renomear
File.Move(@"d:\a.txt", @"d:\a.old");
Gravando um arquivo
StreamWriter writer = new StreamWriter(@"d:\a.txt");
writer.WriteLine("Legal!");
writer.WriteLine("Legal2");
writer.WriteLine("Legal3");
writer.Close();
Lendo o mesmo arquivo - todas as linhas
Console.ForegroundColor = ConsoleColor.Blue;
StreamReader reader = new StreamReader(@"d:\a.txt");
while (!reader.EndOfStream)
{
Console.WriteLine(reader.ReadLine());
}
reader.Close();
Lendo arquivo - todas as linhas - com "Using"
Console.ForegroundColor = ConsoleColor.Green;
using (StreamReader reader2 = new StreamReader(@"d:\a.txt"))
while (!reader2.EndOfStream)
{
Console.WriteLine(reader2.ReadLine());
}
Informações do arquivo
Console.ForegroundColor = ConsoleColor.Red;
FileInfo info = new FileInfo(@"d:\a.txt");
if (info.Exists)
{
Console.WriteLine(info.Attributes);
Console.WriteLine(info.DirectoryName);
Console.WriteLine(info.Length);
}
Obter raiz de página web
Server.MapPath("~/Default.aspx");
Pegar nome de arquivo de um path ou parte do path
string[] auxiliar = NomeArquivo.Split('\\');
string nome = auxiliar[auxiliar.Length - 1];
Criar nome de arquivo temporário
string nomeArquivo = Guid.NewGuid().ToString().Substring(0, 6) + ".zip";