Skip to content

Instantly share code, notes, and snippets.

@alastairtree
Created January 4, 2018 12:40
Show Gist options
  • Save alastairtree/3970425bfa5d26b4582adc39c70dd2e3 to your computer and use it in GitHub Desktop.
Save alastairtree/3970425bfa5d26b4582adc39c70dd2e3 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Util
{
public class FileHelper
{
public bool IsDirectoryEmpty(string path)
{
return !Directory.EnumerateFiles(path).Any();
}
public List<string> GetAllFiles(string path)
{
var files = Directory.GetFiles(path);
return files.Length > 0 ? files.ToList() : new List<string>();
}
public string GetFileNameWithoutExtension(string path)
{
return Path.GetFileNameWithoutExtension(path);
}
public bool IsFileLocked(string path)
{
var locked = false;
try
{
using (File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
}
}
catch (UnauthorizedAccessException)
{
locked = true;
}
catch (IOException)
{
locked = true;
}
return locked;
}
public string GetCombinedPath(string path, string fileName)
{
return Path.Combine(path, fileName);
}
public bool MoveFile(string sourcefile, string destFile, bool overwrite = false)
{
if (File.Exists(sourcefile))
{
if (File.Exists(destFile) && overwrite)
File.Delete(destFile);
File.Move(sourcefile, destFile);
return true;
}
return false;
}
public bool CopyFile(string sourcefile, string destFile, bool overwrite = false)
{
if (File.Exists(sourcefile))
{
if (File.Exists(destFile) && overwrite)
File.Delete(destFile);
File.Copy(sourcefile, destFile);
return true;
}
return false;
}
public void DeleteFiles(string folder, IEnumerable<string> files)
{
foreach (var file in files)
{
File.Delete(GetCombinedPath(folder, file));
}
}
public void DeleteFile(string path, string file)
{
File.Delete(GetCombinedPath(path, file));
}
public bool Exists(string path)
{
return File.Exists(path);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment