Moved file related methods to FileHelpers class

This commit is contained in:
Jaex 2022-05-03 09:34:18 +03:00
parent 23061aa698
commit f60e8dd6f7
78 changed files with 991 additions and 930 deletions

View file

@ -107,7 +107,7 @@ public static bool WriteToFile(this Stream stream, string filePath)
{
if (stream.Length > 0 && !string.IsNullOrEmpty(filePath))
{
Helpers.CreateDirectoryFromFilePath(filePath);
FileHelpers.CreateDirectoryFromFilePath(filePath);
using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read))
{

View file

@ -56,7 +56,7 @@ public ExternalProgram(string name, string path) : this()
public string GetFullPath()
{
return Helpers.ExpandFolderVariables(Path);
return FileHelpers.ExpandFolderVariables(Path);
}
public string Run(string inputPath)
@ -107,7 +107,7 @@ public string Run(string inputPath)
CreateNoWindow = HiddenWindow
};
DebugHelper.WriteLine($"Action input: \"{inputPath}\" [{Helpers.GetFileSizeReadable(inputPath)}]");
DebugHelper.WriteLine($"Action input: \"{inputPath}\" [{FileHelpers.GetFileSizeReadable(inputPath)}]");
DebugHelper.WriteLine($"Action run: \"{psi.FileName}\" {psi.Arguments}");
process.StartInfo = psi;
@ -117,7 +117,7 @@ public string Run(string inputPath)
if (!string.IsNullOrEmpty(outputPath) && File.Exists(outputPath))
{
DebugHelper.WriteLine($"Action output: \"{outputPath}\" [{Helpers.GetFileSizeReadable(outputPath)}]");
DebugHelper.WriteLine($"Action output: \"{outputPath}\" [{FileHelpers.GetFileSizeReadable(outputPath)}]");
if (DeleteInputFile && !inputPath.Equals(outputPath, StringComparison.OrdinalIgnoreCase))
{

View file

@ -57,7 +57,7 @@ private DebugForm(Logger logger)
string startupPath = AppDomain.CurrentDomain.BaseDirectory;
llRunningFrom.Text = startupPath;
llRunningFrom.LinkClicked += (sender, e) => Helpers.OpenFolder(startupPath);
llRunningFrom.LinkClicked += (sender, e) => FileHelpers.OpenFolder(startupPath);
Logger.MessageAdded += logger_MessageAdded;
Activated += (sender, e) => btnUploadLog.Visible = HasUploadRequested;
@ -101,7 +101,7 @@ private void btnCopyAll_Click(object sender, EventArgs e)
private void btnOpenLogFile_Click(object sender, EventArgs e)
{
Helpers.OpenFile(Logger.LogFilePath);
FileHelpers.OpenFile(Logger.LogFilePath);
}
private void btnLoadedAssemblies_Click(object sender, EventArgs e)

View file

@ -76,7 +76,7 @@ private void btnSendBugReport_Click(object sender, EventArgs e)
private void btnOpenLogFile_Click(object sender, EventArgs e)
{
Helpers.OpenFile(LogPath);
FileHelpers.OpenFile(LogPath);
}
private void btnContinue_Click(object sender, EventArgs e)

View file

@ -99,12 +99,12 @@ private void UpdateCompareControls()
private void btnFilePathBrowse_Click(object sender, EventArgs e)
{
Helpers.BrowseFile(txtFilePath);
FileHelpers.BrowseFile(txtFilePath);
}
private void btnFilePathBrowse2_Click(object sender, EventArgs e)
{
Helpers.BrowseFile(txtFilePath2);
FileHelpers.BrowseFile(txtFilePath2);
}
private void cbCompareTwoFiles_CheckedChanged(object sender, EventArgs e)

View file

@ -118,7 +118,7 @@ private void FilterImageFiles()
{
string imageFilePath = Images[i];
bool isImageFile = !string.IsNullOrEmpty(imageFilePath) && Helpers.IsImageFile(imageFilePath);
bool isImageFile = !string.IsNullOrEmpty(imageFilePath) && FileHelpers.IsImageFile(imageFilePath);
if (i == CurrentImageIndex)
{
@ -150,7 +150,7 @@ private void UpdateStatus()
AppendStatus($"{CurrentImageIndex + 1} / {Images.Length}");
}
string fileName = Helpers.GetFileNameSafe(CurrentImageFilePath);
string fileName = FileHelpers.GetFileNameSafe(CurrentImageFilePath);
if (!string.IsNullOrEmpty(fileName))
{

View file

@ -0,0 +1,763 @@
#region License Information (GPL v3)
/*
ShareX - A program that allows you to take screenshots and share any file type
Copyright (c) 2007-2022 ShareX Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Optionally you can also view the license at <http://www.gnu.org/licenses/>.
*/
#endregion License Information (GPL v3)
using Microsoft.VisualBasic.FileIO;
using ShareX.HelpersLib.Properties;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace ShareX.HelpersLib
{
public static class FileHelpers
{
public static readonly string[] ImageFileExtensions = new string[] { "jpg", "jpeg", "png", "gif", "bmp", "ico", "tif", "tiff" };
public static readonly string[] TextFileExtensions = new string[] { "txt", "log", "nfo", "c", "cpp", "cc", "cxx", "h", "hpp", "hxx", "cs", "vb",
"html", "htm", "xhtml", "xht", "xml", "css", "js", "php", "bat", "java", "lua", "py", "pl", "cfg", "ini", "dart", "go", "gohtml" };
public static readonly string[] VideoFileExtensions = new string[] { "mp4", "webm", "mkv", "avi", "vob", "ogv", "ogg", "mov", "qt", "wmv", "m4p",
"m4v", "mpg", "mp2", "mpeg", "mpe", "mpv", "m2v", "m4v", "flv", "f4v" };
public static string GetFileNameExtension(string filePath, bool includeDot = false, bool checkSecondExtension = true)
{
string extension = "";
if (!string.IsNullOrEmpty(filePath))
{
int pos = filePath.LastIndexOf('.');
if (pos >= 0)
{
extension = filePath.Substring(pos + 1);
if (checkSecondExtension)
{
filePath = filePath.Remove(pos);
string extension2 = GetFileNameExtension(filePath, false, false);
if (!string.IsNullOrEmpty(extension2))
{
foreach (string knownExtension in new string[] { "tar" })
{
if (extension2.Equals(knownExtension, StringComparison.OrdinalIgnoreCase))
{
extension = extension2 + "." + extension;
break;
}
}
}
}
if (includeDot)
{
extension = "." + extension;
}
}
}
return extension;
}
public static string GetFileNameSafe(string filePath)
{
if (!string.IsNullOrEmpty(filePath))
{
int pos = filePath.LastIndexOf('\\');
if (pos < 0)
{
pos = filePath.LastIndexOf('/');
}
if (pos >= 0)
{
return filePath.Substring(pos + 1);
}
}
return filePath;
}
public static string ChangeFileNameExtension(string fileName, string extension)
{
if (!string.IsNullOrEmpty(fileName))
{
int pos = fileName.LastIndexOf('.');
if (pos >= 0)
{
fileName = fileName.Remove(pos);
}
if (!string.IsNullOrEmpty(extension))
{
pos = extension.LastIndexOf('.');
if (pos >= 0)
{
extension = extension.Substring(pos + 1);
}
return fileName + "." + extension;
}
}
return fileName;
}
public static string AppendExtension(string filePath, string extension)
{
return filePath.TrimEnd('.') + '.' + extension.TrimStart('.');
}
public static bool CheckExtension(string filePath, IEnumerable<string> extensions)
{
string ext = GetFileNameExtension(filePath);
if (!string.IsNullOrEmpty(ext))
{
return extensions.Any(x => ext.Equals(x, StringComparison.OrdinalIgnoreCase));
}
return false;
}
public static bool IsImageFile(string filePath)
{
return CheckExtension(filePath, ImageFileExtensions);
}
public static bool IsTextFile(string filePath)
{
return CheckExtension(filePath, TextFileExtensions);
}
public static bool IsVideoFile(string filePath)
{
return CheckExtension(filePath, VideoFileExtensions);
}
public static EDataType FindDataType(string filePath)
{
if (IsImageFile(filePath))
{
return EDataType.Image;
}
if (IsTextFile(filePath))
{
return EDataType.Text;
}
return EDataType.File;
}
public static string GetValidFileName(string fileName, string separator = "")
{
char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
if (string.IsNullOrEmpty(separator))
{
return new string(fileName.Where(c => !invalidFileNameChars.Contains(c)).ToArray());
}
else
{
foreach (char invalidFileNameChar in invalidFileNameChars)
{
fileName = fileName.Replace(invalidFileNameChar.ToString(), separator);
}
return fileName.Trim().Replace(separator + separator, separator);
}
}
public static string GetValidFolderPath(string folderPath)
{
char[] invalidPathChars = Path.GetInvalidPathChars();
return new string(folderPath.Where(c => !invalidPathChars.Contains(c)).ToArray());
}
public static string GetValidFilePath(string filePath)
{
string folderPath = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileName(filePath);
return GetValidFolderPath(folderPath) + Path.DirectorySeparatorChar + GetValidFileName(fileName);
}
public static bool OpenFile(string filePath)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
try
{
using (Process process = new Process())
{
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = filePath
};
process.StartInfo = psi;
process.Start();
}
DebugHelper.WriteLine("File opened: " + filePath);
return true;
}
catch (Exception e)
{
DebugHelper.WriteException(e, $"OpenFile({filePath}) failed.");
}
}
else
{
MessageBox.Show(Resources.Helpers_OpenFile_File_not_exist_ + Environment.NewLine + filePath, "ShareX",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return false;
}
public static bool OpenFolder(string folderPath)
{
if (!string.IsNullOrEmpty(folderPath) && Directory.Exists(folderPath))
{
if (!folderPath.EndsWith(@"\"))
{
folderPath += @"\";
}
try
{
using (Process process = new Process())
{
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = folderPath
};
process.StartInfo = psi;
process.Start();
}
DebugHelper.WriteLine("Folder opened: " + folderPath);
return true;
}
catch (Exception e)
{
DebugHelper.WriteException(e, $"OpenFolder({folderPath}) failed.");
}
}
else
{
MessageBox.Show(Resources.Helpers_OpenFolder_Folder_not_exist_ + Environment.NewLine + folderPath, "ShareX",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return false;
}
public static bool OpenFolderWithFile(string filePath)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
try
{
NativeMethods.OpenFolderAndSelectFile(filePath);
DebugHelper.WriteLine("Folder opened with file: " + filePath);
return true;
}
catch (Exception e)
{
DebugHelper.WriteException(e, $"OpenFolderWithFile({filePath}) failed.");
}
}
else
{
MessageBox.Show(Resources.Helpers_OpenFile_File_not_exist_ + Environment.NewLine + filePath, "ShareX",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return false;
}
public static string GetUniqueFilePath(string filePath)
{
if (File.Exists(filePath))
{
string folderPath = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileNameWithoutExtension(filePath);
string fileExtension = Path.GetExtension(filePath);
int number = 1;
Match regex = Regex.Match(fileName, @"^(.+) \((\d+)\)$");
if (regex.Success)
{
fileName = regex.Groups[1].Value;
number = int.Parse(regex.Groups[2].Value);
}
do
{
number++;
string newFileName = $"{fileName} ({number}){fileExtension}";
filePath = Path.Combine(folderPath, newFileName);
}
while (File.Exists(filePath));
}
return filePath;
}
public static bool BrowseFile(TextBox tb, string initialDirectory = "", bool detectSpecialFolders = false)
{
return BrowseFile("ShareX - " + Resources.Helpers_BrowseFile_Choose_file, tb, initialDirectory, detectSpecialFolders);
}
public static bool BrowseFile(string title, TextBox tb, string initialDirectory = "", bool detectSpecialFolders = false)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Title = title;
try
{
string path = tb.Text;
if (detectSpecialFolders)
{
path = ExpandFolderVariables(path);
}
if (!string.IsNullOrEmpty(path))
{
path = Path.GetDirectoryName(path);
if (Directory.Exists(path))
{
ofd.InitialDirectory = path;
}
}
}
finally
{
if (string.IsNullOrEmpty(ofd.InitialDirectory) && !string.IsNullOrEmpty(initialDirectory))
{
ofd.InitialDirectory = initialDirectory;
}
}
if (ofd.ShowDialog() == DialogResult.OK)
{
string fileName = ofd.FileName;
if (detectSpecialFolders)
{
fileName = GetVariableFolderPath(fileName);
}
tb.Text = fileName;
return true;
}
}
return false;
}
public static bool BrowseFolder(TextBox tb, string initialDirectory = "", bool detectSpecialFolders = false)
{
return BrowseFolder("ShareX - " + Resources.Helpers_BrowseFolder_Choose_folder, tb, initialDirectory, detectSpecialFolders);
}
public static bool BrowseFolder(string title, TextBox tb, string initialDirectory = "", bool detectSpecialFolders = false)
{
using (FolderSelectDialog fsd = new FolderSelectDialog())
{
fsd.Title = title;
string path = tb.Text;
if (!string.IsNullOrEmpty(path) && Directory.Exists(path))
{
fsd.InitialDirectory = path;
}
else if (!string.IsNullOrEmpty(initialDirectory))
{
fsd.InitialDirectory = initialDirectory;
}
if (fsd.ShowDialog())
{
tb.Text = detectSpecialFolders ? GetVariableFolderPath(fsd.FileName) : fsd.FileName;
return true;
}
}
return false;
}
public static string GetVariableFolderPath(string path, bool supportCustomSpecialFolders = false)
{
if (!string.IsNullOrEmpty(path))
{
try
{
if (supportCustomSpecialFolders)
{
foreach (KeyValuePair<string, string> specialFolder in HelpersOptions.ShareXSpecialFolders)
{
path = path.Replace(specialFolder.Value, $"%{specialFolder.Key}%", StringComparison.OrdinalIgnoreCase);
}
}
foreach (Environment.SpecialFolder specialFolder in Helpers.GetEnums<Environment.SpecialFolder>())
{
path = path.Replace(Environment.GetFolderPath(specialFolder), $"%{specialFolder}%", StringComparison.OrdinalIgnoreCase);
}
}
catch (Exception e)
{
DebugHelper.WriteException(e);
}
}
return path;
}
public static string ExpandFolderVariables(string path, bool supportCustomSpecialFolders = false)
{
if (!string.IsNullOrEmpty(path))
{
try
{
if (supportCustomSpecialFolders)
{
foreach (KeyValuePair<string, string> specialFolder in HelpersOptions.ShareXSpecialFolders)
{
path = path.Replace($"%{specialFolder.Key}%", specialFolder.Value, StringComparison.OrdinalIgnoreCase);
}
}
foreach (Environment.SpecialFolder specialFolder in Helpers.GetEnums<Environment.SpecialFolder>())
{
path = path.Replace($"%{specialFolder}%", Environment.GetFolderPath(specialFolder), StringComparison.OrdinalIgnoreCase);
}
path = Environment.ExpandEnvironmentVariables(path);
}
catch (Exception e)
{
DebugHelper.WriteException(e);
}
}
return path;
}
public static string OutputSpecialFolders()
{
StringBuilder sb = new StringBuilder();
foreach (Environment.SpecialFolder specialFolder in Helpers.GetEnums<Environment.SpecialFolder>())
{
sb.AppendLine(string.Format("{0,-25}{1}", specialFolder, Environment.GetFolderPath(specialFolder)));
}
return sb.ToString();
}
public static bool IsFileLocked(string filePath)
{
try
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
{
fs.Close();
}
}
catch (IOException)
{
return true;
}
return false;
}
public static long GetFileSize(string filePath)
{
try
{
return new FileInfo(filePath).Length;
}
catch
{
}
return -1;
}
public static string GetFileSizeReadable(string filePath, bool binaryUnits = false)
{
long fileSize = GetFileSize(filePath);
if (fileSize >= 0)
{
return fileSize.ToSizeString(binaryUnits);
}
return "";
}
public static void CreateDirectory(string directoryPath)
{
if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
{
try
{
Directory.CreateDirectory(directoryPath);
}
catch (Exception e)
{
DebugHelper.WriteException(e);
MessageBox.Show(Resources.Helpers_CreateDirectoryIfNotExist_Create_failed_ + "\r\n\r\n" + e, "ShareX - " + Resources.Error,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
public static void CreateDirectoryFromFilePath(string filePath)
{
if (!string.IsNullOrEmpty(filePath))
{
string directoryPath = Path.GetDirectoryName(filePath);
CreateDirectory(directoryPath);
}
}
public static bool IsValidFilePath(string filePath)
{
FileInfo fi = null;
try
{
fi = new FileInfo(filePath);
}
catch (ArgumentException) { }
catch (PathTooLongException) { }
catch (NotSupportedException) { }
return fi != null;
}
public static string CopyFile(string filePath, string destinationFolder, bool overwrite = true)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath) && !string.IsNullOrEmpty(destinationFolder))
{
string fileName = Path.GetFileName(filePath);
string destinationFilePath = Path.Combine(destinationFolder, fileName);
CreateDirectory(destinationFolder);
File.Copy(filePath, destinationFilePath, overwrite);
return destinationFilePath;
}
return null;
}
public static string MoveFile(string filePath, string destinationFolder, bool overwrite = true)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath) && !string.IsNullOrEmpty(destinationFolder))
{
string fileName = Path.GetFileName(filePath);
string destinationFilePath = Path.Combine(destinationFolder, fileName);
CreateDirectory(destinationFolder);
if (overwrite && File.Exists(destinationFilePath))
{
File.Delete(destinationFilePath);
}
File.Move(filePath, destinationFilePath);
return destinationFilePath;
}
return null;
}
public static string RenameFile(string filePath, string newFileName)
{
try
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
string directory = Path.GetDirectoryName(filePath);
string newFilePath = Path.Combine(directory, newFileName);
File.Move(filePath, newFilePath);
return newFilePath;
}
}
catch (Exception e)
{
MessageBox.Show("Rename file error:\r\n" + e.ToString(), "ShareX - " + Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return filePath;
}
public static bool DeleteFile(string filePath, bool sendToRecycleBin = false)
{
try
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
if (sendToRecycleBin)
{
FileSystem.DeleteFile(filePath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
}
else
{
File.Delete(filePath);
}
return true;
}
}
catch (Exception e)
{
DebugHelper.WriteException(e);
}
return false;
}
public static string BackupFileWeekly(string filePath, string destinationFolder)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
string fileName = Path.GetFileNameWithoutExtension(filePath);
DateTime dateTime = DateTime.Now;
string extension = Path.GetExtension(filePath);
string newFileName = string.Format("{0}-{1:yyyy-MM}-W{2:00}{3}", fileName, dateTime, dateTime.WeekOfYear(), extension);
string newFilePath = Path.Combine(destinationFolder, newFileName);
if (!File.Exists(newFilePath))
{
CreateDirectory(destinationFolder);
File.Copy(filePath, newFilePath, false);
return newFilePath;
}
}
return null;
}
public static void BackupFileMonthly(string filePath, string destinationFolder)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
string fileName = Path.GetFileNameWithoutExtension(filePath);
string extension = Path.GetExtension(filePath);
string newFileName = string.Format("{0}-{1:yyyy-MM}{2}", fileName, DateTime.Now, extension);
string newFilePath = Path.Combine(destinationFolder, newFileName);
if (!File.Exists(newFilePath))
{
CreateDirectory(destinationFolder);
File.Copy(filePath, newFilePath, false);
}
}
}
public static string GetAbsolutePath(string path)
{
path = ExpandFolderVariables(path);
if (!Path.IsPathRooted(path)) // Is relative path?
{
path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
}
return Path.GetFullPath(path);
}
public static string GetTempFilePath(string extension)
{
string path = Path.GetTempFileName();
return Path.ChangeExtension(path, extension);
}
public static void CopyAll(string sourceDirectory, string targetDirectory)
{
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
CopyAll(diSource, diTarget);
}
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
if (!Directory.Exists(target.FullName))
{
Directory.CreateDirectory(target.FullName);
}
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
public static void CreateEmptyFile(string filePath)
{
File.Create(filePath).Dispose();
}
public static IEnumerable<string> GetFilesByExtensions(string directoryPath, params string[] extensions)
{
return GetFilesByExtensions(new DirectoryInfo(directoryPath), extensions);
}
public static IEnumerable<string> GetFilesByExtensions(DirectoryInfo directoryInfo, params string[] extensions)
{
HashSet<string> allowedExtensions = new HashSet<string>(extensions, StringComparer.OrdinalIgnoreCase);
return directoryInfo.EnumerateFiles().Where(f => allowedExtensions.Contains(f.Extension)).Select(x => x.FullName);
}
}
}

View file

@ -23,7 +23,6 @@
#endregion License Information (GPL v3)
using Microsoft.VisualBasic.FileIO;
using Microsoft.Win32;
using Newtonsoft.Json.Linq;
using ShareX.HelpersLib.Properties;
@ -66,10 +65,6 @@ public static class Helpers
public const string Base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; // https://en.wikipedia.org/wiki/Base58
public const string Base56 = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz"; // A variant, Base56, excludes 1 (one) and o (lowercase o) compared to Base 58.
public static readonly string[] ImageFileExtensions = new string[] { "jpg", "jpeg", "png", "gif", "bmp", "ico", "tif", "tiff" };
public static readonly string[] TextFileExtensions = new string[] { "txt", "log", "nfo", "c", "cpp", "cc", "cxx", "h", "hpp", "hxx", "cs", "vb", "html", "htm", "xhtml", "xht", "xml", "css", "js", "php", "bat", "java", "lua", "py", "pl", "cfg", "ini", "dart", "go", "gohtml" };
public static readonly string[] VideoFileExtensions = new string[] { "mp4", "webm", "mkv", "avi", "vob", "ogv", "ogg", "mov", "qt", "wmv", "m4p", "m4v", "mpg", "mp2", "mpeg", "mpe", "mpv", "m2v", "m4v", "flv", "f4v" };
public static readonly Version OSVersion = Environment.OSVersion.Version;
private static Cursor[] cursorList;
@ -93,140 +88,6 @@ public static Cursor[] CursorList
}
}
public static string GetFileNameExtension(string filePath, bool includeDot = false, bool checkSecondExtension = true)
{
string extension = "";
if (!string.IsNullOrEmpty(filePath))
{
int pos = filePath.LastIndexOf('.');
if (pos >= 0)
{
extension = filePath.Substring(pos + 1);
if (checkSecondExtension)
{
filePath = filePath.Remove(pos);
string extension2 = GetFileNameExtension(filePath, false, false);
if (!string.IsNullOrEmpty(extension2))
{
foreach (string knownExtension in new string[] { "tar" })
{
if (extension2.Equals(knownExtension, StringComparison.OrdinalIgnoreCase))
{
extension = extension2 + "." + extension;
break;
}
}
}
}
if (includeDot)
{
extension = "." + extension;
}
}
}
return extension;
}
public static string GetFileNameSafe(string filePath)
{
if (!string.IsNullOrEmpty(filePath))
{
int pos = filePath.LastIndexOf('\\');
if (pos < 0)
{
pos = filePath.LastIndexOf('/');
}
if (pos >= 0)
{
return filePath.Substring(pos + 1);
}
}
return filePath;
}
public static string ChangeFileNameExtension(string fileName, string extension)
{
if (!string.IsNullOrEmpty(fileName))
{
int pos = fileName.LastIndexOf('.');
if (pos >= 0)
{
fileName = fileName.Remove(pos);
}
if (!string.IsNullOrEmpty(extension))
{
pos = extension.LastIndexOf('.');
if (pos >= 0)
{
extension = extension.Substring(pos + 1);
}
return fileName + "." + extension;
}
}
return fileName;
}
public static string AppendExtension(string filePath, string extension)
{
return filePath.TrimEnd('.') + '.' + extension.TrimStart('.');
}
public static bool CheckExtension(string filePath, IEnumerable<string> extensions)
{
string ext = GetFileNameExtension(filePath);
if (!string.IsNullOrEmpty(ext))
{
return extensions.Any(x => ext.Equals(x, StringComparison.OrdinalIgnoreCase));
}
return false;
}
public static bool IsImageFile(string filePath)
{
return CheckExtension(filePath, ImageFileExtensions);
}
public static bool IsTextFile(string filePath)
{
return CheckExtension(filePath, TextFileExtensions);
}
public static bool IsVideoFile(string filePath)
{
return CheckExtension(filePath, VideoFileExtensions);
}
public static EDataType FindDataType(string filePath)
{
if (IsImageFile(filePath))
{
return EDataType.Image;
}
if (IsTextFile(filePath))
{
return EDataType.Text;
}
return EDataType.File;
}
public static string AddZeroes(string input, int digits = 2)
{
return input.PadLeft(digits, '0');
@ -301,44 +162,12 @@ public static string GetRandomLine(string text)
return null;
}
public static string GetRandomLineFromFile(string path)
public static string GetRandomLineFromFile(string filePath)
{
string text = File.ReadAllText(path, Encoding.UTF8);
string text = File.ReadAllText(filePath, Encoding.UTF8);
return GetRandomLine(text);
}
public static string GetValidFileName(string fileName, string separator = "")
{
char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
if (string.IsNullOrEmpty(separator))
{
return new string(fileName.Where(c => !invalidFileNameChars.Contains(c)).ToArray());
}
else
{
foreach (char invalidFileNameChar in invalidFileNameChars)
{
fileName = fileName.Replace(invalidFileNameChar.ToString(), separator);
}
return fileName.Trim().Replace(separator + separator, separator);
}
}
public static string GetValidFolderPath(string folderPath)
{
char[] invalidPathChars = Path.GetInvalidPathChars();
return new string(folderPath.Where(c => !invalidPathChars.Contains(c)).ToArray());
}
public static string GetValidFilePath(string filePath)
{
string folderPath = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileName(filePath);
return GetValidFolderPath(folderPath) + Path.DirectorySeparatorChar + GetValidFileName(fileName);
}
public static string GetValidURL(string url, bool replaceSpace = false)
{
if (replaceSpace) url = url.Replace(' ', '_');
@ -449,104 +278,6 @@ public static string GetProperName(string name, bool keepCase = false)
return sb.ToString();
}
public static bool OpenFile(string filePath)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
try
{
using (Process process = new Process())
{
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = filePath
};
process.StartInfo = psi;
process.Start();
}
DebugHelper.WriteLine("File opened: " + filePath);
return true;
}
catch (Exception e)
{
DebugHelper.WriteException(e, $"OpenFile({filePath}) failed.");
}
}
else
{
MessageBox.Show(Resources.Helpers_OpenFile_File_not_exist_ + Environment.NewLine + filePath, "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return false;
}
public static bool OpenFolder(string folderPath)
{
if (!string.IsNullOrEmpty(folderPath) && Directory.Exists(folderPath))
{
if (!folderPath.EndsWith(@"\"))
{
folderPath += @"\";
}
try
{
using (Process process = new Process())
{
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = folderPath
};
process.StartInfo = psi;
process.Start();
}
DebugHelper.WriteLine("Folder opened: " + folderPath);
return true;
}
catch (Exception e)
{
DebugHelper.WriteException(e, $"OpenFolder({folderPath}) failed.");
}
}
else
{
MessageBox.Show(Resources.Helpers_OpenFolder_Folder_not_exist_ + Environment.NewLine + folderPath, "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return false;
}
public static bool OpenFolderWithFile(string filePath)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
try
{
NativeMethods.OpenFolderAndSelectFile(filePath);
DebugHelper.WriteLine("Folder opened with file: " + filePath);
return true;
}
catch (Exception e)
{
DebugHelper.WriteException(e, $"OpenFolderWithFile({filePath}) failed.");
}
}
else
{
MessageBox.Show(Resources.Helpers_OpenFile_File_not_exist_ + Environment.NewLine + filePath, "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return false;
}
/// <summary>
/// If version1 newer than version2 = 1
/// If version1 equal to version2 = 0
@ -642,35 +373,6 @@ public static bool IsValidIPAddress(string ip)
return Regex.IsMatch(ip.Trim(), pattern);
}
public static string GetUniqueFilePath(string filePath)
{
if (File.Exists(filePath))
{
string folderPath = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileNameWithoutExtension(filePath);
string fileExtension = Path.GetExtension(filePath);
int number = 1;
Match regex = Regex.Match(fileName, @"^(.+) \((\d+)\)$");
if (regex.Success)
{
fileName = regex.Groups[1].Value;
number = int.Parse(regex.Groups[2].Value);
}
do
{
number++;
string newFileName = $"{fileName} ({number}){fileExtension}";
filePath = Path.Combine(folderPath, newFileName);
}
while (File.Exists(filePath));
}
return filePath;
}
public static string ProperTimeSpan(TimeSpan ts)
{
string time = string.Format("{0:00}:{1:00}", ts.Minutes, ts.Seconds);
@ -719,164 +421,6 @@ public static void PlaySoundAsync(string filePath)
}
}
public static bool BrowseFile(TextBox tb, string initialDirectory = "", bool detectSpecialFolders = false)
{
return BrowseFile("ShareX - " + Resources.Helpers_BrowseFile_Choose_file, tb, initialDirectory, detectSpecialFolders);
}
public static bool BrowseFile(string title, TextBox tb, string initialDirectory = "", bool detectSpecialFolders = false)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Title = title;
try
{
string path = tb.Text;
if (detectSpecialFolders)
{
path = ExpandFolderVariables(path);
}
if (!string.IsNullOrEmpty(path))
{
path = Path.GetDirectoryName(path);
if (Directory.Exists(path))
{
ofd.InitialDirectory = path;
}
}
}
finally
{
if (string.IsNullOrEmpty(ofd.InitialDirectory) && !string.IsNullOrEmpty(initialDirectory))
{
ofd.InitialDirectory = initialDirectory;
}
}
if (ofd.ShowDialog() == DialogResult.OK)
{
string fileName = ofd.FileName;
if (detectSpecialFolders)
{
fileName = GetVariableFolderPath(fileName);
}
tb.Text = fileName;
return true;
}
}
return false;
}
public static bool BrowseFolder(TextBox tb, string initialDirectory = "", bool detectSpecialFolders = false)
{
return BrowseFolder("ShareX - " + Resources.Helpers_BrowseFolder_Choose_folder, tb, initialDirectory, detectSpecialFolders);
}
public static bool BrowseFolder(string title, TextBox tb, string initialDirectory = "", bool detectSpecialFolders = false)
{
using (FolderSelectDialog fsd = new FolderSelectDialog())
{
fsd.Title = title;
string path = tb.Text;
if (!string.IsNullOrEmpty(path) && Directory.Exists(path))
{
fsd.InitialDirectory = path;
}
else if (!string.IsNullOrEmpty(initialDirectory))
{
fsd.InitialDirectory = initialDirectory;
}
if (fsd.ShowDialog())
{
tb.Text = detectSpecialFolders ? GetVariableFolderPath(fsd.FileName) : fsd.FileName;
return true;
}
}
return false;
}
public static string GetVariableFolderPath(string path, bool supportCustomSpecialFolders = false)
{
if (!string.IsNullOrEmpty(path))
{
try
{
if (supportCustomSpecialFolders)
{
foreach (KeyValuePair<string, string> specialFolder in HelpersOptions.ShareXSpecialFolders)
{
path = path.Replace(specialFolder.Value, $"%{specialFolder.Key}%", StringComparison.OrdinalIgnoreCase);
}
}
foreach (Environment.SpecialFolder specialFolder in GetEnums<Environment.SpecialFolder>())
{
path = path.Replace(Environment.GetFolderPath(specialFolder), $"%{specialFolder}%", StringComparison.OrdinalIgnoreCase);
}
}
catch (Exception e)
{
DebugHelper.WriteException(e);
}
}
return path;
}
public static string ExpandFolderVariables(string path, bool supportCustomSpecialFolders = false)
{
if (!string.IsNullOrEmpty(path))
{
try
{
if (supportCustomSpecialFolders)
{
foreach (KeyValuePair<string, string> specialFolder in HelpersOptions.ShareXSpecialFolders)
{
path = path.Replace($"%{specialFolder.Key}%", specialFolder.Value, StringComparison.OrdinalIgnoreCase);
}
}
foreach (Environment.SpecialFolder specialFolder in GetEnums<Environment.SpecialFolder>())
{
path = path.Replace($"%{specialFolder}%", Environment.GetFolderPath(specialFolder), StringComparison.OrdinalIgnoreCase);
}
path = Environment.ExpandEnvironmentVariables(path);
}
catch (Exception e)
{
DebugHelper.WriteException(e);
}
}
return path;
}
public static string OutputSpecialFolders()
{
StringBuilder sb = new StringBuilder();
foreach (Environment.SpecialFolder specialFolder in GetEnums<Environment.SpecialFolder>())
{
sb.AppendLine(string.Format("{0,-25}{1}", specialFolder, Environment.GetFolderPath(specialFolder)));
}
return sb.ToString();
}
public static bool WaitWhile(Func<bool> check, int interval, int timeout = -1)
{
Stopwatch timer = Stopwatch.StartNew();
@ -911,207 +455,6 @@ public static async Task WaitWhileAsync(Func<bool> check, int interval, int time
if (result) onSuccess();
}
public static bool IsFileLocked(string filePath)
{
try
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
{
fs.Close();
}
}
catch (IOException)
{
return true;
}
return false;
}
public static long GetFileSize(string filePath)
{
try
{
return new FileInfo(filePath).Length;
}
catch
{
}
return -1;
}
public static string GetFileSizeReadable(string filePath, bool binaryUnits = false)
{
long fileSize = GetFileSize(filePath);
if (fileSize >= 0)
{
return fileSize.ToSizeString(binaryUnits);
}
return "";
}
public static void CreateDirectory(string directoryPath)
{
if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
{
try
{
Directory.CreateDirectory(directoryPath);
}
catch (Exception e)
{
DebugHelper.WriteException(e);
MessageBox.Show(Resources.Helpers_CreateDirectoryIfNotExist_Create_failed_ + "\r\n\r\n" + e, "ShareX - " + Resources.Error,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
public static void CreateDirectoryFromFilePath(string filePath)
{
if (!string.IsNullOrEmpty(filePath))
{
string directoryPath = Path.GetDirectoryName(filePath);
CreateDirectory(directoryPath);
}
}
public static bool IsValidFilePath(string path)
{
FileInfo fi = null;
try
{
fi = new FileInfo(path);
}
catch (ArgumentException) { }
catch (PathTooLongException) { }
catch (NotSupportedException) { }
return fi != null;
}
public static string CopyFile(string filePath, string destinationFolder, bool overwrite = true)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath) && !string.IsNullOrEmpty(destinationFolder))
{
string fileName = Path.GetFileName(filePath);
string destinationFilePath = Path.Combine(destinationFolder, fileName);
CreateDirectory(destinationFolder);
File.Copy(filePath, destinationFilePath, overwrite);
return destinationFilePath;
}
return null;
}
public static string MoveFile(string filePath, string destinationFolder, bool overwrite = true)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath) && !string.IsNullOrEmpty(destinationFolder))
{
string fileName = Path.GetFileName(filePath);
string destinationFilePath = Path.Combine(destinationFolder, fileName);
CreateDirectory(destinationFolder);
if (overwrite && File.Exists(destinationFilePath))
{
File.Delete(destinationFilePath);
}
File.Move(filePath, destinationFilePath);
return destinationFilePath;
}
return null;
}
public static string RenameFile(string filePath, string newFileName)
{
try
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
string directory = Path.GetDirectoryName(filePath);
string newFilePath = Path.Combine(directory, newFileName);
File.Move(filePath, newFilePath);
return newFilePath;
}
}
catch (Exception e)
{
MessageBox.Show("Rename file error:\r\n" + e.ToString(), "ShareX - " + Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return filePath;
}
public static bool DeleteFile(string filePath, bool sendToRecycleBin = false)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
try
{
if (sendToRecycleBin)
{
FileSystem.DeleteFile(filePath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
}
else
{
File.Delete(filePath);
}
return true;
}
catch (Exception e)
{
DebugHelper.WriteException(e);
}
}
return false;
}
public static string BackupFileWeekly(string filePath, string destinationFolder)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
string fileName = Path.GetFileNameWithoutExtension(filePath);
DateTime dateTime = DateTime.Now;
string extension = Path.GetExtension(filePath);
string newFileName = string.Format("{0}-{1:yyyy-MM}-W{2:00}{3}", fileName, dateTime, dateTime.WeekOfYear(), extension);
string newFilePath = Path.Combine(destinationFolder, newFileName);
if (!File.Exists(newFilePath))
{
CreateDirectory(destinationFolder);
File.Copy(filePath, newFilePath, false);
return newFilePath;
}
}
return null;
}
public static void BackupFileMonthly(string filePath, string destinationFolder)
{
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
string fileName = Path.GetFileNameWithoutExtension(filePath);
string extension = Path.GetExtension(filePath);
string newFileName = string.Format("{0}-{1:yyyy-MM}{2}", fileName, DateTime.Now, extension);
string newFilePath = Path.Combine(destinationFolder, newFileName);
if (!File.Exists(newFilePath))
{
CreateDirectory(destinationFolder);
File.Copy(filePath, newFilePath, false);
}
}
}
public static string GetUniqueID()
{
return Guid.NewGuid().ToString("N");
@ -1247,24 +590,6 @@ public static void SetDefaultUICulture(CultureInfo culture)
}
}
public static string GetAbsolutePath(string path)
{
path = ExpandFolderVariables(path);
if (!Path.IsPathRooted(path)) // Is relative path?
{
path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
}
return Path.GetFullPath(path);
}
public static string GetTempFilePath(string extension)
{
string path = Path.GetTempFileName();
return Path.ChangeExtension(path, extension);
}
public static bool IsAdministrator()
{
try
@ -1324,33 +649,6 @@ public static bool IsRunning(string name)
return true;
}
public static void CopyAll(string sourceDirectory, string targetDirectory)
{
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
CopyAll(diSource, diTarget);
}
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
if (!Directory.Exists(target.FullName))
{
Directory.CreateDirectory(target.FullName);
}
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
public static T ByteArrayToStructure<T>(byte[] bytes) where T : struct
{
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
@ -1478,11 +776,6 @@ public static byte[] ComputeHMACSHA256(string data, byte[] key)
return ComputeHMACSHA256(Encoding.UTF8.GetBytes(data), key);
}
public static void CreateEmptyFile(string path)
{
File.Create(path).Dispose();
}
public static string SafeStringFormat(string format, params object[] args)
{
return SafeStringFormat(null, format, args);
@ -1615,17 +908,6 @@ public static string XMLFormat(string xml)
}
}
public static IEnumerable<string> GetFilesByExtensions(string directoryPath, params string[] extensions)
{
return GetFilesByExtensions(new DirectoryInfo(directoryPath), extensions);
}
public static IEnumerable<string> GetFilesByExtensions(DirectoryInfo directoryInfo, params string[] extensions)
{
HashSet<string> allowedExtensions = new HashSet<string>(extensions, StringComparer.OrdinalIgnoreCase);
return directoryInfo.EnumerateFiles().Where(f => allowedExtensions.Contains(f.Extension)).Select(x => x.FullName);
}
public static Icon GetProgressIcon(int percentage)
{
return GetProgressIcon(percentage, Color.FromArgb(16, 116, 193));

View file

@ -1767,7 +1767,7 @@ public static string[] OpenImageFileDialog(bool multiselect, Form form = null, s
public static ImageFormat GetImageFormat(string filePath)
{
ImageFormat imageFormat = ImageFormat.Png;
string ext = Helpers.GetFileNameExtension(filePath);
string ext = FileHelpers.GetFileNameExtension(filePath);
if (!string.IsNullOrEmpty(ext))
{
@ -1799,7 +1799,7 @@ public static ImageFormat GetImageFormat(string filePath)
public static bool SaveImage(Image img, string filePath)
{
Helpers.CreateDirectoryFromFilePath(filePath);
FileHelpers.CreateDirectoryFromFilePath(filePath);
ImageFormat imageFormat = GetImageFormat(filePath);
try
@ -1840,7 +1840,7 @@ public static string SaveImageFileDialog(Image img, string filePath = "", bool u
sfd.FileName = Path.GetFileName(filePath);
string ext = Helpers.GetFileNameExtension(filePath);
string ext = FileHelpers.GetFileNameExtension(filePath);
if (!string.IsNullOrEmpty(ext))
{
@ -1890,9 +1890,9 @@ public static Bitmap LoadImage(string filePath)
{
try
{
filePath = Helpers.GetAbsolutePath(filePath);
filePath = FileHelpers.GetAbsolutePath(filePath);
if (!string.IsNullOrEmpty(filePath) && Helpers.IsImageFile(filePath) && File.Exists(filePath))
if (!string.IsNullOrEmpty(filePath) && FileHelpers.IsImageFile(filePath) && File.Exists(filePath))
{
// http://stackoverflow.com/questions/788335/why-does-image-fromfile-keep-a-file-handle-open-sometimes
Bitmap bmp = (Bitmap)Image.FromStream(new MemoryStream(File.ReadAllBytes(filePath)));

View file

@ -91,7 +91,7 @@ public static class JsonHelpers
{
if (!string.IsNullOrEmpty(filePath))
{
Helpers.CreateDirectoryFromFilePath(filePath);
FileHelpers.CreateDirectoryFromFilePath(filePath);
using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, FileOptions.WriteThrough))
{

View file

@ -57,7 +57,7 @@ public Logger(string logFilePath)
{
FileWrite = true;
LogFilePath = logFilePath;
Helpers.CreateDirectoryFromFilePath(LogFilePath);
FileHelpers.CreateDirectoryFromFilePath(LogFilePath);
}
protected void OnMessageAdded(string message)

View file

@ -250,7 +250,7 @@ public string Parse(string pattern)
{
string path = entry.Item2;
if (Helpers.IsTextFile(path))
if (FileHelpers.IsTextFile(path))
{
return Helpers.GetRandomLineFromFile(path);
}
@ -307,15 +307,15 @@ public string Parse(string pattern)
if (Type == NameParserType.FolderPath)
{
result = Helpers.GetValidFolderPath(result);
result = FileHelpers.GetValidFolderPath(result);
}
else if (Type == NameParserType.FileName)
{
result = Helpers.GetValidFileName(result);
result = FileHelpers.GetValidFileName(result);
}
else if (Type == NameParserType.FilePath)
{
result = Helpers.GetValidFilePath(result);
result = FileHelpers.GetValidFilePath(result);
}
else if (Type == NameParserType.URL)
{

View file

@ -63,7 +63,7 @@ public string ProcessFilePath
}
}
public string ProcessFileName => Helpers.GetFileNameSafe(ProcessFilePath);
public string ProcessFileName => FileHelpers.GetFileNameSafe(ProcessFilePath);
public int ProcessId
{

View file

@ -132,7 +132,7 @@ private bool SaveInternal(string filePath)
{
lock (this)
{
Helpers.CreateDirectoryFromFilePath(filePath);
FileHelpers.CreateDirectoryFromFilePath(filePath);
string tempFilePath = filePath + ".temp";
@ -154,7 +154,7 @@ private bool SaveInternal(string filePath)
{
string fileName = Path.GetFileName(filePath);
backupFilePath = Path.Combine(BackupFolder, fileName);
Helpers.CreateDirectory(BackupFolder);
FileHelpers.CreateDirectory(BackupFolder);
}
File.Replace(tempFilePath, filePath, backupFilePath);
@ -166,7 +166,7 @@ private bool SaveInternal(string filePath)
if (CreateWeeklyBackup && !string.IsNullOrEmpty(BackupFolder))
{
Helpers.BackupFileWeekly(filePath, BackupFolder);
FileHelpers.BackupFileWeekly(filePath, BackupFolder);
}
isSuccess = true;

View file

@ -36,7 +36,7 @@ public class SevenZipManager
public SevenZipManager()
{
SevenZipPath = Helpers.GetAbsolutePath("7za.exe");
SevenZipPath = FileHelpers.GetAbsolutePath("7za.exe");
}
public SevenZipManager(string sevenZipPath)

View file

@ -164,6 +164,7 @@
</Compile>
<Compile Include="FPSManager.cs" />
<Compile Include="Helpers\ClipboardHelpersEx.cs" />
<Compile Include="Helpers\FileHelpers.cs" />
<Compile Include="Helpers\JsonHelpers.cs" />
<Compile Include="TimerResolutionManager.cs" />
<Compile Include="ImageFilesCache.cs" />

View file

@ -45,7 +45,7 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide
if (dlg.ShowDialog())
{
value = Helpers.GetVariableFolderPath(dlg.FileName, true);
value = FileHelpers.GetVariableFolderPath(dlg.FileName, true);
}
}

View file

@ -44,7 +44,7 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide
if (!string.IsNullOrEmpty(filePath))
{
filePath = Helpers.ExpandFolderVariables(filePath, true);
filePath = FileHelpers.ExpandFolderVariables(filePath, true);
string directoryPath = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(directoryPath) && Directory.Exists(directoryPath))
@ -57,7 +57,7 @@ public override object EditValue(ITypeDescriptorContext context, IServiceProvide
if (!string.IsNullOrEmpty(filePath))
{
value = Helpers.GetVariableFolderPath(filePath, true);
value = FileHelpers.GetVariableFolderPath(filePath, true);
}
return value;

View file

@ -216,7 +216,7 @@ private void StartDownload()
btnAction.Text = Resources.DownloaderForm_StartDownload_Cancel;
string folderPath = Path.Combine(Path.GetTempPath(), "ShareX");
Helpers.CreateDirectory(folderPath);
FileHelpers.CreateDirectory(folderPath);
DownloadLocation = Path.Combine(folderPath, FileName);
DebugHelper.WriteLine($"Downloading: \"{URL}\" -> \"{DownloadLocation}\"");

View file

@ -127,7 +127,7 @@ public static void Compress(string source, string archivePath, CompressionLevel
public static void Compress(string archivePath, List<ZipEntryInfo> entries, CompressionLevel compression = CompressionLevel.Optimal)
{
Helpers.CreateDirectoryFromFilePath(archivePath);
FileHelpers.CreateDirectoryFromFilePath(archivePath);
if (File.Exists(archivePath))
{

View file

@ -352,7 +352,7 @@ private string OutputStats(HistoryItem[] historyItems)
IEnumerable<string> fileExtensions = historyItems.
Where(x => !string.IsNullOrEmpty(x.FileName) && !x.FileName.EndsWith(")")).
Select(x => Helpers.GetFileNameExtension(x.FileName)).
Select(x => FileHelpers.GetFileNameExtension(x.FileName)).
GroupBy(x => string.IsNullOrWhiteSpace(x) ? empty : x).
OrderByDescending(x => x.Count()).
Select(x => string.Format("[{0}] {1}", x.Count(), x.Key));

View file

@ -138,7 +138,7 @@ private IEnumerable<HistoryItem> GetHistoryItems(bool mockData = false)
{
HistoryItem hi = historyItems[i];
if (!string.IsNullOrEmpty(hi.FilePath) && Helpers.IsImageFile(hi.FilePath) &&
if (!string.IsNullOrEmpty(hi.FilePath) && FileHelpers.IsImageFile(hi.FilePath) &&
(regex == null || regex.IsMatch(hi.FileName) || (SearchInTags && hi.Tags != null && hi.Tags.Any(tag => regex.IsMatch(tag.Value)))) &&
(!Settings.FilterMissingFiles || File.Exists(hi.FilePath)))
{

View file

@ -85,12 +85,12 @@ public HistoryItem UpdateSelectedHistoryItem()
IsShortenedURLExist = !string.IsNullOrEmpty(HistoryItem.ShortenedURL);
IsThumbnailURLExist = !string.IsNullOrEmpty(HistoryItem.ThumbnailURL);
IsDeletionURLExist = !string.IsNullOrEmpty(HistoryItem.DeletionURL);
IsImageURL = IsURLExist && Helpers.IsImageFile(HistoryItem.URL);
IsTextURL = IsURLExist && Helpers.IsTextFile(HistoryItem.URL);
IsImageURL = IsURLExist && FileHelpers.IsImageFile(HistoryItem.URL);
IsTextURL = IsURLExist && FileHelpers.IsTextFile(HistoryItem.URL);
IsFilePathValid = !string.IsNullOrEmpty(HistoryItem.FilePath) && Path.HasExtension(HistoryItem.FilePath);
IsFileExist = IsFilePathValid && File.Exists(HistoryItem.FilePath);
IsImageFile = IsFileExist && Helpers.IsImageFile(HistoryItem.FilePath);
IsTextFile = IsFileExist && Helpers.IsTextFile(HistoryItem.FilePath);
IsImageFile = IsFileExist && FileHelpers.IsImageFile(HistoryItem.FilePath);
IsTextFile = IsFileExist && FileHelpers.IsTextFile(HistoryItem.FilePath);
UpdateContextMenu(historyItems.Length);
}
@ -172,12 +172,12 @@ public void OpenDeletionURL()
public void OpenFile()
{
if (HistoryItem != null && IsFileExist) Helpers.OpenFile(HistoryItem.FilePath);
if (HistoryItem != null && IsFileExist) FileHelpers.OpenFile(HistoryItem.FilePath);
}
public void OpenFolder()
{
if (HistoryItem != null && IsFileExist) Helpers.OpenFolderWithFile(HistoryItem.FilePath);
if (HistoryItem != null && IsFileExist) FileHelpers.OpenFolderWithFile(HistoryItem.FilePath);
}
public void TryOpen()
@ -194,7 +194,7 @@ public void TryOpen()
}
else if (IsFileExist)
{
Helpers.OpenFile(HistoryItem.FilePath);
FileHelpers.OpenFile(HistoryItem.FilePath);
}
}
}
@ -280,7 +280,8 @@ public void CopyFile()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.FilePath) && Path.HasExtension(x.FilePath) && File.Exists(x.FilePath)).Select(x => x.FilePath).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.FilePath) && Path.HasExtension(x.FilePath) &&
File.Exists(x.FilePath)).Select(x => x.FilePath).ToArray();
if (array != null && array.Length > 0)
{
@ -304,7 +305,8 @@ public void CopyHTMLLink()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL)).Select(x => string.Format("<a href=\"{0}\">{0}</a>", x.URL)).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL)).
Select(x => string.Format("<a href=\"{0}\">{0}</a>", x.URL)).ToArray();
if (array != null && array.Length > 0)
{
@ -323,7 +325,8 @@ public void CopyHTMLImage()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL) && Helpers.IsImageFile(x.URL)).Select(x => string.Format("<img src=\"{0}\"/>", x.URL)).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL) && FileHelpers.IsImageFile(x.URL)).
Select(x => string.Format("<img src=\"{0}\"/>", x.URL)).ToArray();
if (array != null && array.Length > 0)
{
@ -342,7 +345,8 @@ public void CopyHTMLLinkedImage()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL) && Helpers.IsImageFile(x.URL) && !string.IsNullOrEmpty(x.ThumbnailURL)).Select(x => string.Format("<a href=\"{0}\"><img src=\"{1}\"/></a>", x.URL, x.ThumbnailURL)).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL) && FileHelpers.IsImageFile(x.URL) &&
!string.IsNullOrEmpty(x.ThumbnailURL)).Select(x => string.Format("<a href=\"{0}\"><img src=\"{1}\"/></a>", x.URL, x.ThumbnailURL)).ToArray();
if (array != null && array.Length > 0)
{
@ -380,7 +384,8 @@ public void CopyForumImage()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL) && Helpers.IsImageFile(x.URL)).Select(x => string.Format("[img]{0}[/img]", x.URL)).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL) && FileHelpers.IsImageFile(x.URL)).
Select(x => string.Format("[img]{0}[/img]", x.URL)).ToArray();
if (array != null && array.Length > 0)
{
@ -399,7 +404,8 @@ public void CopyForumLinkedImage()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL) && Helpers.IsImageFile(x.URL) && !string.IsNullOrEmpty(x.ThumbnailURL)).Select(x => string.Format("[url={0}][img]{1}[/img][/url]", x.URL, x.ThumbnailURL)).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL) && FileHelpers.IsImageFile(x.URL) &&
!string.IsNullOrEmpty(x.ThumbnailURL)).Select(x => string.Format("[url={0}][img]{1}[/img][/url]", x.URL, x.ThumbnailURL)).ToArray();
if (array != null && array.Length > 0)
{
@ -418,7 +424,8 @@ public void CopyMarkdownLink()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL)).Select(x => string.Format("[{0}]({1})", x.FileName, x.URL)).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL)).
Select(x => string.Format("[{0}]({1})", x.FileName, x.URL)).ToArray();
if (array != null && array.Length > 0)
{
@ -437,7 +444,8 @@ public void CopyMarkdownImage()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL) && Helpers.IsImageFile(x.URL)).Select(x => string.Format("![{0}]({1})", x.FileName, x.URL)).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL) && FileHelpers.IsImageFile(x.URL)).
Select(x => string.Format("![{0}]({1})", x.FileName, x.URL)).ToArray();
if (array != null && array.Length > 0)
{
@ -456,7 +464,8 @@ public void CopyMarkdownLinkedImage()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL) && Helpers.IsImageFile(x.URL) && !string.IsNullOrEmpty(x.ThumbnailURL)).Select(x => string.Format("[![{0}]({1})]({2})", x.FileName, x.ThumbnailURL, x.URL)).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.URL) && FileHelpers.IsImageFile(x.URL) &&
!string.IsNullOrEmpty(x.ThumbnailURL)).Select(x => string.Format("[![{0}]({1})]({2})", x.FileName, x.ThumbnailURL, x.URL)).ToArray();
if (array != null && array.Length > 0)
{
@ -475,7 +484,8 @@ public void CopyFilePath()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.FilePath) && Path.HasExtension(x.FilePath) && File.Exists(x.FilePath)).Select(x => x.FilePath).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.FilePath) && Path.HasExtension(x.FilePath) &&
File.Exists(x.FilePath)).Select(x => x.FilePath).ToArray();
if (array != null && array.Length > 0)
{
@ -494,7 +504,8 @@ public void CopyFileName()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.FilePath) && Path.HasExtension(x.FilePath)).Select(x => Path.GetFileNameWithoutExtension(x.FilePath)).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.FilePath) && Path.HasExtension(x.FilePath)).
Select(x => Path.GetFileNameWithoutExtension(x.FilePath)).ToArray();
if (array != null && array.Length > 0)
{
@ -513,7 +524,8 @@ public void CopyFileNameWithExtension()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.FilePath) && Path.HasExtension(x.FilePath)).Select(x => Path.GetFileName(x.FilePath)).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.FilePath) && Path.HasExtension(x.FilePath)).
Select(x => Path.GetFileName(x.FilePath)).ToArray();
if (array != null && array.Length > 0)
{
@ -532,7 +544,8 @@ public void CopyFolder()
HistoryItem[] historyItems = OnGetHistoryItems();
if (historyItems != null)
{
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.FilePath) && Path.HasExtension(x.FilePath)).Select(x => Path.GetDirectoryName(x.FilePath)).ToArray();
string[] array = historyItems.Where(x => x != null && !string.IsNullOrEmpty(x.FilePath) && Path.HasExtension(x.FilePath)).
Select(x => Path.GetDirectoryName(x.FilePath)).ToArray();
if (array != null && array.Length > 0)
{

View file

@ -113,12 +113,12 @@ protected void Backup(string filePath)
{
if (CreateBackup)
{
Helpers.CopyFile(filePath, BackupFolder);
FileHelpers.CopyFile(filePath, BackupFolder);
}
if (CreateWeeklyBackup)
{
Helpers.BackupFileWeekly(filePath, BackupFolder);
FileHelpers.BackupFileWeekly(filePath, BackupFolder);
}
}
}

View file

@ -66,7 +66,7 @@ protected override bool Append(string filePath, IEnumerable<HistoryItem> history
{
lock (thisLock)
{
Helpers.CreateDirectoryFromFilePath(filePath);
FileHelpers.CreateDirectoryFromFilePath(filePath);
using (FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read, 4096, FileOptions.WriteThrough))
using (StreamWriter streamWriter = new StreamWriter(fileStream))

View file

@ -135,7 +135,7 @@ protected override bool Append(string filePath, IEnumerable<HistoryItem> history
{
lock (thisLock)
{
Helpers.CreateDirectoryFromFilePath(filePath);
FileHelpers.CreateDirectoryFromFilePath(filePath);
using (FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read, 4096, FileOptions.WriteThrough))
using (XmlTextWriter writer = new XmlTextWriter(fileStream, Encoding.UTF8))

View file

@ -94,7 +94,7 @@ public override Bitmap Apply(Bitmap bmp)
return bmp;
}
string imageFilePath = Helpers.ExpandFolderVariables(ImageLocation, true);
string imageFilePath = FileHelpers.ExpandFolderVariables(ImageLocation, true);
if (!string.IsNullOrEmpty(imageFilePath) && File.Exists(imageFilePath))
{

View file

@ -99,11 +99,11 @@ public DrawParticles()
public override Bitmap Apply(Bitmap bmp)
{
string imageFolder = Helpers.ExpandFolderVariables(ImageFolder, true);
string imageFolder = FileHelpers.ExpandFolderVariables(ImageFolder, true);
if (!string.IsNullOrEmpty(imageFolder) && Directory.Exists(imageFolder))
{
string[] files = Helpers.GetFilesByExtensions(imageFolder, ".png", ".jpg").ToArray();
string[] files = FileHelpers.GetFilesByExtensions(imageFolder, ".png", ".jpg").ToArray();
if (files.Length > 0)
{

View file

@ -56,7 +56,7 @@ public ImageEffectPackagerForm(string json, string name, string imageEffectsFold
private void btnOpenImageEffectsFolder_Click(object sender, EventArgs e)
{
Helpers.OpenFolder(ShareXImageEffectsFolderPath);
FileHelpers.OpenFolder(ShareXImageEffectsFolderPath);
}
private void txtAssetsFolderPath_TextChanged(object sender, EventArgs e)
@ -66,7 +66,7 @@ private void txtAssetsFolderPath_TextChanged(object sender, EventArgs e)
private void btnAssetsFolderPathBrowse_Click(object sender, EventArgs e)
{
Helpers.BrowseFolder(txtAssetsFolderPath, ShareXImageEffectsFolderPath);
FileHelpers.BrowseFolder(txtAssetsFolderPath, ShareXImageEffectsFolderPath);
}
private void txtPackageFilePath_TextChanged(object sender, EventArgs e)
@ -106,7 +106,7 @@ private void btnPackage_Click(object sender, EventArgs e)
if (!string.IsNullOrEmpty(outputFilePath) && File.Exists(outputFilePath))
{
Helpers.OpenFolderWithFile(outputFilePath);
FileHelpers.OpenFolderWithFile(outputFilePath);
}
}
}

View file

@ -830,7 +830,7 @@ private void pbResult_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
{
if (e.Data.GetData(DataFormats.FileDrop, false) is string[] files && files.Length > 0 && Helpers.IsImageFile(files[0]))
if (e.Data.GetData(DataFormats.FileDrop, false) is string[] files && files.Length > 0 && FileHelpers.IsImageFile(files[0]))
{
if (PreviewImage != null) PreviewImage.Dispose();
PreviewImage = ImageHelpers.LoadImage(files[0]);

View file

@ -51,7 +51,7 @@ public static string Package(string outputFilePath, string configJson, string as
string parentFolderPath = Directory.GetParent(assetsFolderPath).FullName;
int entryNamePosition = parentFolderPath.Length + 1;
foreach (string assetPath in Directory.EnumerateFiles(assetsFolderPath, "*.*", SearchOption.AllDirectories).Where(x => Helpers.IsImageFile(x)))
foreach (string assetPath in Directory.EnumerateFiles(assetsFolderPath, "*.*", SearchOption.AllDirectories).Where(x => FileHelpers.IsImageFile(x)))
{
string entryName = assetPath.Substring(entryNamePosition);
entries.Add(new ZipEntryInfo(assetPath, entryName));
@ -74,7 +74,7 @@ public static string ExtractPackage(string packageFilePath, string destination)
{
ZipManager.Extract(packageFilePath, destination, true, entry =>
{
if (Helpers.IsImageFile(entry.Name))
if (FileHelpers.IsImageFile(entry.Name))
{
return true;
}

View file

@ -61,7 +61,7 @@ private async void btnBrowseFolder_Click(object sender, EventArgs e)
private async Task BrowseFolder()
{
if (Helpers.BrowseFolder(txtFolderPath))
if (FileHelpers.BrowseFolder(txtFolderPath))
{
await IndexFolder();
}

View file

@ -112,7 +112,7 @@ private void txtOutputFolder_TextChanged(object sender, EventArgs e)
private void BtnOutputFolderBrowse_Click(object sender, EventArgs e)
{
Helpers.BrowseFolder(txtOutputFolder);
FileHelpers.BrowseFolder(txtOutputFolder);
}
private void nudColumnCount_ValueChanged(object sender, EventArgs e)
@ -144,7 +144,7 @@ private async void BtnSplitImage_Click(object sender, EventArgs e)
if (filePaths.Count > 0)
{
Helpers.OpenFolderWithFile(filePaths[0]);
FileHelpers.OpenFolderWithFile(filePaths[0]);
}
}
catch (Exception ex)

View file

@ -133,7 +133,7 @@ private void txtOutputFolder_TextChanged(object sender, EventArgs e)
private void btnOutputFolder_Click(object sender, EventArgs e)
{
Helpers.BrowseFolder(txtOutputFolder);
FileHelpers.BrowseFolder(txtOutputFolder);
}
private void txtOutputFilename_TextChanged(object sender, EventArgs e)

View file

@ -189,7 +189,7 @@ private bool StartEncoding()
if (Options.AutoOpenFolder && result && !ffmpeg.StopRequested)
{
Helpers.OpenFolderWithFile(outputFilePath);
FileHelpers.OpenFolderWithFile(outputFilePath);
}
}
catch (Exception e)
@ -239,7 +239,7 @@ private void txtOutputFolder_TextChanged(object sender, EventArgs e)
private void btnOutputFolderBrowse_Click(object sender, EventArgs e)
{
Helpers.BrowseFolder(txtOutputFolder);
FileHelpers.BrowseFolder(txtOutputFolder);
}
private void txtOutputFileName_TextChanged(object sender, EventArgs e)

View file

@ -103,7 +103,7 @@ protected void OnThumbnailsTaken(List<VideoThumbnailInfo> thumbnails)
private void btnBrowse_Click(object sender, EventArgs e)
{
Helpers.BrowseFile(Resources.VideoThumbnailerForm_btnBrowse_Click_Browse_for_media_file, txtMediaPath);
FileHelpers.BrowseFile(Resources.VideoThumbnailerForm_btnBrowse_Click_Browse_for_media_file, txtMediaPath);
}
}
}

View file

@ -145,7 +145,7 @@ private List<VideoThumbnailInfo> Finish(List<VideoThumbnailInfo> tempThumbnails)
if (Options.OpenDirectory && thumbnails.Count > 0)
{
Helpers.OpenFolderWithFile(thumbnails[0].FilePath);
FileHelpers.OpenFolderWithFile(thumbnails[0].FilePath);
}
}
@ -171,11 +171,11 @@ private string GetOutputDirectory()
directory = Path.GetDirectoryName(MediaPath);
break;
case ThumbnailLocationType.CustomFolder:
directory = Helpers.ExpandFolderVariables(Options.CustomOutputDirectory);
directory = FileHelpers.ExpandFolderVariables(Options.CustomOutputDirectory);
break;
}
Helpers.CreateDirectory(directory);
FileHelpers.CreateDirectory(directory);
return directory;
}

View file

@ -43,8 +43,8 @@ private static void Main(string[] args)
if (!string.IsNullOrEmpty(input))
{
string filePath = Helpers.GetAbsolutePath("ShareX.exe");
string tempFilePath = Helpers.GetTempFilePath("json");
string filePath = FileHelpers.GetAbsolutePath("ShareX.exe");
string tempFilePath = FileHelpers.GetTempFilePath("json");
File.WriteAllText(tempFilePath, input, Encoding.UTF8);
string argument = $"-NativeMessagingInput \"{tempFilePath}\"";
NativeMethods.CreateProcess(filePath, argument, CreateProcessFlags.CREATE_BREAKAWAY_FROM_JOB);

View file

@ -85,7 +85,7 @@ private void btnLoadImageFromClipboard_Click(object sender, EventArgs e)
if (files != null)
{
string imageFilePath = files.FirstOrDefault(x => Helpers.IsImageFile(x));
string imageFilePath = files.FirstOrDefault(x => FileHelpers.IsImageFile(x));
LoadImageFile(imageFilePath);
}
}

View file

@ -281,7 +281,7 @@ private void txtFFmpegPath_TextChanged(object sender, EventArgs e)
private async void buttonFFmpegBrowse_Click(object sender, EventArgs e)
{
if (Helpers.BrowseFile(Resources.FFmpegOptionsForm_buttonFFmpegBrowse_Click_Browse_for_ffmpeg_exe, txtFFmpegPath, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), true))
if (FileHelpers.BrowseFile(Resources.FFmpegOptionsForm_buttonFFmpegBrowse_Click_Browse_for_ffmpeg_exe, txtFFmpegPath, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), true))
{
await RefreshSourcesAsync();
}
@ -306,7 +306,7 @@ private void cbAudioSource_SelectedIndexChanged(object sender, EventArgs e)
private async void btnInstallHelperDevices_Click(object sender, EventArgs e)
{
string filePath = Helpers.GetAbsolutePath("Recorder-devices-setup.exe");
string filePath = FileHelpers.GetAbsolutePath("Recorder-devices-setup.exe");
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
@ -548,7 +548,7 @@ private void DownloaderForm_InstallRequested(string filePath)
{
this.InvokeSafe(async () =>
{
txtFFmpegPath.Text = Helpers.GetVariableFolderPath(Path.Combine(DefaultToolsFolder, "ffmpeg.exe"));
txtFFmpegPath.Text = FileHelpers.GetVariableFolderPath(Path.Combine(DefaultToolsFolder, "ffmpeg.exe"));
await RefreshSourcesAsync();
if (!IsDisposed) UpdateUI();
});

View file

@ -300,7 +300,7 @@ internal void UpdateTitle()
title.AppendFormat(" ({0}%)", zoomPercentage);
}
string fileName = Helpers.GetFileNameSafe(ImageFilePath);
string fileName = FileHelpers.GetFileNameSafe(ImageFilePath);
if (!string.IsNullOrEmpty(fileName))
{

View file

@ -91,11 +91,11 @@ private void LoadImageFiles()
if (tscbStickers.SelectedItem is StickerPackInfo stickerPack && !string.IsNullOrEmpty(stickerPack.FolderPath))
{
string folderPath = Helpers.GetAbsolutePath(stickerPack.FolderPath);
string folderPath = FileHelpers.GetAbsolutePath(stickerPack.FolderPath);
if (Directory.Exists(folderPath))
{
imageFiles = Directory.GetFiles(folderPath).Where(x => Helpers.IsImageFile(x)).ToArray();
imageFiles = Directory.GetFiles(folderPath).Where(x => FileHelpers.IsImageFile(x)).ToArray();
UpdateImageFiles();
}

View file

@ -123,7 +123,7 @@ private void txtFolder_TextChanged(object sender, EventArgs e)
private void btnFolderBrowse_Click(object sender, EventArgs e)
{
Helpers.BrowseFolder(txtFolder, txtFolder.Text);
FileHelpers.BrowseFolder(txtFolder, txtFolder.Text);
}
private void txtName_TextChanged(object sender, EventArgs e)

View file

@ -85,7 +85,7 @@ public string FFmpegPath
if (!string.IsNullOrEmpty(CLIPath))
{
return Helpers.GetAbsolutePath(CLIPath);
return FileHelpers.GetAbsolutePath(CLIPath);
}
return "";
@ -158,7 +158,7 @@ public FFmpegOptions()
public FFmpegOptions(string ffmpegPath)
{
CLIPath = Helpers.GetVariableFolderPath(ffmpegPath);
CLIPath = FileHelpers.GetVariableFolderPath(ffmpegPath);
}
}
}

View file

@ -52,7 +52,7 @@ public int Count
public HardDiskCache(ScreenRecordingOptions options)
{
Options = options;
Helpers.CreateDirectoryFromFilePath(Options.OutputPath);
FileHelpers.CreateDirectoryFromFilePath(Options.OutputPath);
fsCache = new FileStream(Options.OutputPath, FileMode.Create, FileAccess.Write, FileShare.Read);
indexList = new List<LocationInfo>();
}

View file

@ -121,7 +121,7 @@ public ScreenRecorder(ScreenRecordOutput outputType, ScreenRecordingOptions opti
{
default:
case ScreenRecordOutput.FFmpeg:
Helpers.CreateDirectoryFromFilePath(Options.OutputPath);
FileHelpers.CreateDirectoryFromFilePath(Options.OutputPath);
ffmpeg = new FFmpegCLIManager(Options.FFmpeg.FFmpegPath);
ffmpeg.ShowError = true;
ffmpeg.EncodeStarted += OnRecordingStarted;
@ -210,7 +210,7 @@ public void SaveAsGIF(string path, GIFQuality quality)
{
if (imgCache != null && imgCache is HardDiskCache && !IsRecording)
{
Helpers.CreateDirectoryFromFilePath(path);
FileHelpers.CreateDirectoryFromFilePath(path);
HardDiskCache hdCache = imgCache as HardDiskCache;
@ -235,7 +235,7 @@ public void SaveAsGIF(string path, GIFQuality quality)
public bool FFmpegEncodeVideo(string input, string output)
{
Helpers.CreateDirectoryFromFilePath(output);
FileHelpers.CreateDirectoryFromFilePath(output);
Options.IsRecording = false;
Options.IsLossless = false;
@ -256,7 +256,7 @@ public bool FFmpegEncodeVideo(string input, string output)
public bool FFmpegEncodeAsGIF(string input, string output)
{
Helpers.CreateDirectoryFromFilePath(output);
FileHelpers.CreateDirectoryFromFilePath(output);
try
{

View file

@ -1713,7 +1713,7 @@ private void PasteFromClipboard(bool insertMousePosition)
if (files != null)
{
string imageFilePath = files.FirstOrDefault(x => Helpers.IsImageFile(x));
string imageFilePath = files.FirstOrDefault(x => FileHelpers.IsImageFile(x));
if (!string.IsNullOrEmpty(imageFilePath))
{

View file

@ -203,7 +203,7 @@ private static void Main(string[] args)
if (AppVeyor)
{
Helpers.CopyAll(OutputDir, ParentDir);
FileHelpers.CopyAll(OutputDir, ParentDir);
}
if (Job.HasFlag(SetupJobs.OpenOutputDirectory))
@ -314,15 +314,15 @@ private static void CreateFolder(string source, string destination, SetupJobs jo
SetupHelpers.CopyFiles(Path.Combine(source, language), "*.resources.dll", Path.Combine(destination, "Languages", language));
}
Helpers.CopyAll(Path.Combine(ParentDir, @"ShareX.ScreenCaptureLib\Stickers"), Path.Combine(destination, "Stickers"));
FileHelpers.CopyAll(Path.Combine(ParentDir, @"ShareX.ScreenCaptureLib\Stickers"), Path.Combine(destination, "Stickers"));
if (job == SetupJobs.CreateMicrosoftStoreFolder || job == SetupJobs.CreateMicrosoftStoreDebugFolder)
{
Helpers.CopyAll(MicrosoftStorePackageFilesDir, destination);
FileHelpers.CopyAll(MicrosoftStorePackageFilesDir, destination);
}
else if (job == SetupJobs.CreatePortable)
{
Helpers.CreateEmptyFile(Path.Combine(destination, "Portable"));
FileHelpers.CreateEmptyFile(Path.Combine(destination, "Portable"));
FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(ReleaseExecutablePath);
string zipFileName = string.Format("ShareX-{0}.{1}.{2}-portable.zip", versionInfo.ProductMajorPart, versionInfo.ProductMinorPart, versionInfo.ProductBuildPart);

View file

@ -268,9 +268,9 @@ private string GetUploadPath(string fileName)
{
string path = NameParser.Parse(NameParserType.FolderPath, Settings.ObjectPrefix.Trim('/'));
if ((Settings.RemoveExtensionImage && Helpers.IsImageFile(fileName)) ||
(Settings.RemoveExtensionText && Helpers.IsTextFile(fileName)) ||
(Settings.RemoveExtensionVideo && Helpers.IsVideoFile(fileName)))
if ((Settings.RemoveExtensionImage && FileHelpers.IsImageFile(fileName)) ||
(Settings.RemoveExtensionText && FileHelpers.IsTextFile(fileName)) ||
(Settings.RemoveExtensionVideo && FileHelpers.IsVideoFile(fileName)))
{
fileName = Path.GetFileNameWithoutExtension(fileName);
}

View file

@ -142,9 +142,9 @@ private string GetUploadPath(string fileName)
{
string uploadPath = NameParser.Parse(NameParserType.FolderPath, Prefix.Trim('/'));
if ((RemoveExtensionImage && Helpers.IsImageFile(fileName)) ||
(RemoveExtensionText && Helpers.IsTextFile(fileName)) ||
(RemoveExtensionVideo && Helpers.IsVideoFile(fileName)))
if ((RemoveExtensionImage && FileHelpers.IsImageFile(fileName)) ||
(RemoveExtensionText && FileHelpers.IsTextFile(fileName)) ||
(RemoveExtensionVideo && FileHelpers.IsVideoFile(fileName)))
{
fileName = Path.GetFileNameWithoutExtension(fileName);
}

View file

@ -74,7 +74,7 @@ public string LocalUri
return "";
}
return new Uri(Helpers.ExpandFolderVariables(LocalhostRoot)).AbsoluteUri;
return new Uri(FileHelpers.ExpandFolderVariables(LocalhostRoot)).AbsoluteUri;
}
}
@ -112,7 +112,7 @@ public LocalhostAccount()
public string GetSubFolderPath()
{
return NameParser.Parse(NameParserType.URL, SubFolderPath.Replace("%host", Helpers.ExpandFolderVariables(LocalhostRoot)));
return NameParser.Parse(NameParserType.URL, SubFolderPath.Replace("%host", FileHelpers.ExpandFolderVariables(LocalhostRoot)));
}
public string GetHttpHomePath()
@ -126,7 +126,7 @@ public string GetHttpHomePath()
HttpHomePath = URLHelpers.RemovePrefixes(HttpHomePath);
return NameParser.Parse(NameParserType.URL, HttpHomePath.Replace("%host", Helpers.ExpandFolderVariables(LocalhostRoot)));
return NameParser.Parse(NameParserType.URL, HttpHomePath.Replace("%host", FileHelpers.ExpandFolderVariables(LocalhostRoot)));
}
public string GetUriPath(string fileName)
@ -189,7 +189,7 @@ public string GetLocalhostPath(string fileName)
return "";
}
return Path.Combine(Path.Combine(Helpers.ExpandFolderVariables(LocalhostRoot), GetSubFolderPath()), fileName);
return Path.Combine(Path.Combine(FileHelpers.ExpandFolderVariables(LocalhostRoot), GetSubFolderPath()), fileName);
}
public string GetLocalhostUri(string fileName)
@ -206,7 +206,7 @@ public string GetLocalhostUri(string fileName)
public override string ToString()
{
return string.Format("{0} - {1}:{2}", Name, Helpers.GetVariableFolderPath(LocalhostRoot), Port);
return string.Format("{0} - {1}:{2}", Name, FileHelpers.GetVariableFolderPath(LocalhostRoot), Port);
}
public LocalhostAccount Clone()

View file

@ -184,7 +184,7 @@ public string ShareFile(string path, string fileName)
OwnCloudShareResponseData data = ((JObject)result.ocs.data).ToObject<OwnCloudShareResponseData>();
string link = data.url;
if (PreviewLink && Helpers.IsImageFile(path))
if (PreviewLink && FileHelpers.IsImageFile(path))
{
link += "/preview";
}

View file

@ -88,7 +88,7 @@ public override UploadResult Upload(Stream stream, string fileName)
string filePath = account.GetLocalhostPath(fileName);
Helpers.CreateDirectoryFromFilePath(filePath);
FileHelpers.CreateDirectoryFromFilePath(filePath);
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{

View file

@ -298,7 +298,7 @@ private UploadResult InternalUpload(Stream stream, string fileName, bool refresh
string fileFormName;
if (Helpers.IsVideoFile(fileName))
if (FileHelpers.IsVideoFile(fileName))
{
fileFormName = "video";
}

View file

@ -90,7 +90,7 @@ public override UploadResult UploadText(string text, string fileName)
if (UseFileExtension)
{
string ext = Helpers.GetFileNameExtension(fileName);
string ext = FileHelpers.GetFileNameExtension(fileName);
if (!string.IsNullOrEmpty(ext) && !ext.Equals("txt", StringComparison.InvariantCultureIgnoreCase))
{

View file

@ -48,7 +48,7 @@ public UploaderFilter(string uploader, params string[] extensions)
public bool IsValidFilter(string fileName)
{
string extension = Helpers.GetFileNameExtension(fileName);
string extension = FileHelpers.GetFileNameExtension(fileName);
return !string.IsNullOrEmpty(extension) && Extensions.Any(x => x.TrimStart('.').Equals(extension, StringComparison.OrdinalIgnoreCase));
}

View file

@ -430,7 +430,7 @@ private void ExecuteClickAction(ThumbnailViewClickAction clickAction, TaskInfo i
case ThumbnailViewClickAction.Default:
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
if (Helpers.IsImageFile(filePath))
if (FileHelpers.IsImageFile(filePath))
{
pbThumbnail.Enabled = false;
@ -443,15 +443,16 @@ private void ExecuteClickAction(ThumbnailViewClickAction clickAction, TaskInfo i
pbThumbnail.Enabled = true;
}
}
else if (Helpers.IsTextFile(filePath) || Helpers.IsVideoFile(filePath) || MessageBox.Show("Would you like to open this file?" + "\r\n\r\n" + filePath,
else if (FileHelpers.IsTextFile(filePath) || FileHelpers.IsVideoFile(filePath) ||
MessageBox.Show("Would you like to open this file?" + "\r\n\r\n" + filePath,
Resources.ShareXConfirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Helpers.OpenFile(filePath);
FileHelpers.OpenFile(filePath);
}
}
break;
case ThumbnailViewClickAction.OpenImageViewer:
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath) && Helpers.IsImageFile(filePath))
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath) && FileHelpers.IsImageFile(filePath))
{
pbThumbnail.Enabled = false;
@ -468,13 +469,13 @@ private void ExecuteClickAction(ThumbnailViewClickAction clickAction, TaskInfo i
case ThumbnailViewClickAction.OpenFile:
if (!string.IsNullOrEmpty(filePath))
{
Helpers.OpenFile(filePath);
FileHelpers.OpenFile(filePath);
}
break;
case ThumbnailViewClickAction.OpenFolder:
if (!string.IsNullOrEmpty(filePath))
{
Helpers.OpenFolderWithFile(filePath);
FileHelpers.OpenFolderWithFile(filePath);
}
break;
case ThumbnailViewClickAction.OpenURL:
@ -484,7 +485,7 @@ private void ExecuteClickAction(ThumbnailViewClickAction clickAction, TaskInfo i
}
break;
case ThumbnailViewClickAction.EditImage:
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath) && Helpers.IsImageFile(filePath))
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath) && FileHelpers.IsImageFile(filePath))
{
TaskHelpers.AnnotateImageFromFile(filePath);
}
@ -510,7 +511,7 @@ private void LblTitle_MouseClick(object sender, MouseEventArgs e)
if (!string.IsNullOrEmpty(Task.Info.FilePath))
{
Helpers.OpenFile(Task.Info.FilePath);
FileHelpers.OpenFile(Task.Info.FilePath);
}
}
}

View file

@ -141,12 +141,12 @@ private void rtb_LinkClicked(object sender, LinkClickedEventArgs e)
private void btnShareXLicense_Click(object sender, EventArgs e)
{
Helpers.OpenFile(Helpers.GetAbsolutePath("Licenses\\ShareX_license.txt"));
FileHelpers.OpenFile(FileHelpers.GetAbsolutePath("Licenses\\ShareX_license.txt"));
}
private void btnLicenses_Click(object sender, EventArgs e)
{
Helpers.OpenFolder(Helpers.GetAbsolutePath("Licenses"));
FileHelpers.OpenFolder(FileHelpers.GetAbsolutePath("Licenses"));
}
private void btnClose_Click(object sender, EventArgs e)

View file

@ -56,7 +56,7 @@ public ActionsForm(ExternalProgram fileAction)
private void btnPathBrowse_Click(object sender, EventArgs e)
{
Helpers.BrowseFile(txtPath, "", true);
FileHelpers.BrowseFile(txtPath, "", true);
}
private void txtOutputExtension_TextChanged(object sender, EventArgs e)

View file

@ -70,7 +70,7 @@ public AfterCaptureForm(TaskMetadata metadata, TaskSettings taskSettings) : this
public AfterCaptureForm(string filePath, TaskSettings taskSettings) : this(taskSettings)
{
if (Helpers.IsImageFile(filePath))
if (FileHelpers.IsImageFile(filePath))
{
pbImage.LoadImageFromFileAsync(filePath);
}

View file

@ -75,7 +75,7 @@ public AfterUploadForm(TaskInfo info)
foreach (LinkFormatEnum type in Helpers.GetEnums<LinkFormatEnum>())
{
if (!Helpers.IsImageFile(Info.Result.URL) &&
if (!FileHelpers.IsImageFile(Info.Result.URL) &&
(type == LinkFormatEnum.HTMLImage || type == LinkFormatEnum.HTMLLinkedImage ||
type == LinkFormatEnum.ForumImage || type == LinkFormatEnum.ForumLinkedImage ||
type == LinkFormatEnum.WikiImage || type == LinkFormatEnum.WikiLinkedImage))
@ -84,7 +84,7 @@ public AfterUploadForm(TaskInfo info)
AddFormat(type.GetLocalizedDescription(), GetUrlByType(type));
}
if (Helpers.IsImageFile(Info.Result.URL))
if (FileHelpers.IsImageFile(Info.Result.URL))
{
foreach (ClipboardFormat cf in Program.Settings.ClipboardContentFormats)
{
@ -136,7 +136,7 @@ private void tmrClose_Tick(object sender, EventArgs e)
private void btnCopyImage_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Info.FilePath) && Helpers.IsImageFile(Info.FilePath) && File.Exists(Info.FilePath))
if (!string.IsNullOrEmpty(Info.FilePath) && FileHelpers.IsImageFile(Info.FilePath) && File.Exists(Info.FilePath))
{
ClipboardHelpers.CopyImageFromFile(Info.FilePath);
}
@ -176,12 +176,12 @@ private void btnOpenLink_Click(object sender, EventArgs e)
private void btnOpenFile_Click(object sender, EventArgs e)
{
Helpers.OpenFile(Info.FilePath);
FileHelpers.OpenFile(Info.FilePath);
}
private void btnFolderOpen_Click(object sender, EventArgs e)
{
Helpers.OpenFolderWithFile(Info.FilePath);
FileHelpers.OpenFolderWithFile(Info.FilePath);
}
private void btnClose_Click(object sender, EventArgs e)

View file

@ -334,7 +334,7 @@ private void UpdatePersonalFolderPathPreview()
{
try
{
string personalPath = Helpers.GetValidFolderPath(txtPersonalFolderPath.Text);
string personalPath = FileHelpers.GetValidFolderPath(txtPersonalFolderPath.Text);
if (string.IsNullOrEmpty(personalPath))
{
@ -349,7 +349,7 @@ private void UpdatePersonalFolderPathPreview()
}
else
{
personalPath = Helpers.GetAbsolutePath(personalPath);
personalPath = FileHelpers.GetAbsolutePath(personalPath);
}
lblPreviewPersonalFolderPath.Text = personalPath;
@ -665,13 +665,13 @@ private void txtPersonalFolderPath_TextChanged(object sender, EventArgs e)
private void btnBrowsePersonalFolderPath_Click(object sender, EventArgs e)
{
Helpers.BrowseFolder(Resources.ApplicationSettingsForm_btnBrowsePersonalFolderPath_Click_Choose_ShareX_personal_folder_path,
FileHelpers.BrowseFolder(Resources.ApplicationSettingsForm_btnBrowsePersonalFolderPath_Click_Choose_ShareX_personal_folder_path,
txtPersonalFolderPath, Program.PersonalFolder, true);
}
private void btnPersonalFolderPathApply_Click(object sender, EventArgs e)
{
string currentPersonalPath = Helpers.GetValidFolderPath(txtPersonalFolderPath.Text);
string currentPersonalPath = FileHelpers.GetValidFolderPath(txtPersonalFolderPath.Text);
if (!currentPersonalPath.Equals(lastPersonalPath, StringComparison.OrdinalIgnoreCase) && Program.WritePersonalPathConfig(currentPersonalPath))
{
@ -688,7 +688,7 @@ private void btnPersonalFolderPathApply_Click(object sender, EventArgs e)
private void btnOpenPersonalFolder_Click(object sender, EventArgs e)
{
Helpers.OpenFolder(lblPreviewPersonalFolderPath.Text);
FileHelpers.OpenFolder(lblPreviewPersonalFolderPath.Text);
}
private void cbUseCustomScreenshotsPath_CheckedChanged(object sender, EventArgs e)
@ -699,30 +699,30 @@ private void cbUseCustomScreenshotsPath_CheckedChanged(object sender, EventArgs
private void txtCustomScreenshotsPath_TextChanged(object sender, EventArgs e)
{
Program.Settings.CustomScreenshotsPath = Helpers.GetValidFolderPath(txtCustomScreenshotsPath.Text);
Program.Settings.CustomScreenshotsPath = FileHelpers.GetValidFolderPath(txtCustomScreenshotsPath.Text);
UpdateScreenshotsFolderPathPreview();
}
private void btnBrowseCustomScreenshotsPath_Click(object sender, EventArgs e)
{
Helpers.BrowseFolder(Resources.ApplicationSettingsForm_btnBrowseCustomScreenshotsPath_Click_Choose_screenshots_folder_path,
FileHelpers.BrowseFolder(Resources.ApplicationSettingsForm_btnBrowseCustomScreenshotsPath_Click_Choose_screenshots_folder_path,
txtCustomScreenshotsPath, Program.PersonalFolder, true);
}
private void txtSaveImageSubFolderPattern_TextChanged(object sender, EventArgs e)
{
Program.Settings.SaveImageSubFolderPattern = Helpers.GetValidFolderPath(txtSaveImageSubFolderPattern.Text);
Program.Settings.SaveImageSubFolderPattern = FileHelpers.GetValidFolderPath(txtSaveImageSubFolderPattern.Text);
UpdateScreenshotsFolderPathPreview();
}
private void btnOpenScreenshotsFolder_Click(object sender, EventArgs e)
{
Helpers.OpenFolder(lblSaveImageSubFolderPatternPreview.Text);
FileHelpers.OpenFolder(lblSaveImageSubFolderPatternPreview.Text);
}
private void txtSaveImageSubFolderPatternWindow_TextChanged(object sender, EventArgs e)
{
Program.Settings.SaveImageSubFolderPatternWindow = Helpers.GetValidFolderPath(txtSaveImageSubFolderPatternWindow.Text);
Program.Settings.SaveImageSubFolderPatternWindow = FileHelpers.GetValidFolderPath(txtSaveImageSubFolderPatternWindow.Text);
}
#endregion Paths

View file

@ -47,7 +47,7 @@ public FileExistForm(string filePath)
fileName = Path.GetFileNameWithoutExtension(FilePath);
txtNewName.Text = fileName;
btnOverwrite.Text += Path.GetFileName(FilePath);
uniqueFilePath = Helpers.GetUniqueFilePath(FilePath);
uniqueFilePath = FileHelpers.GetUniqueFilePath(FilePath);
btnUniqueName.Text += Path.GetFileName(uniqueFilePath);
}

View file

@ -336,7 +336,7 @@ private void ExecuteAction(ToastClickAction action)
switch (action)
{
case ToastClickAction.AnnotateImage:
if (!string.IsNullOrEmpty(Config.FilePath) && Helpers.IsImageFile(Config.FilePath))
if (!string.IsNullOrEmpty(Config.FilePath) && FileHelpers.IsImageFile(Config.FilePath))
{
TaskHelpers.AnnotateImageFromFile(Config.FilePath);
}
@ -368,13 +368,13 @@ private void ExecuteAction(ToastClickAction action)
case ToastClickAction.OpenFile:
if (!string.IsNullOrEmpty(Config.FilePath))
{
Helpers.OpenFile(Config.FilePath);
FileHelpers.OpenFile(Config.FilePath);
}
break;
case ToastClickAction.OpenFolder:
if (!string.IsNullOrEmpty(Config.FilePath))
{
Helpers.OpenFolderWithFile(Config.FilePath);
FileHelpers.OpenFolderWithFile(Config.FilePath);
}
break;
case ToastClickAction.OpenUrl:

View file

@ -794,7 +794,7 @@ private void txtScreenshotsFolder_TextChanged(object sender, EventArgs e)
private void btnScreenshotsFolderBrowse_Click(object sender, EventArgs e)
{
Helpers.BrowseFolder(Resources.ApplicationSettingsForm_btnBrowseCustomScreenshotsPath_Click_Choose_screenshots_folder_path,
FileHelpers.BrowseFolder(Resources.ApplicationSettingsForm_btnBrowseCustomScreenshotsPath_Click_Choose_screenshots_folder_path,
txtScreenshotsFolder, TaskSettings.ScreenshotsFolder, true);
}
@ -882,7 +882,7 @@ private void txtCustomCaptureSoundPath_TextChanged(object sender, EventArgs e)
private void btnCustomCaptureSoundPath_Click(object sender, EventArgs e)
{
Helpers.BrowseFile(txtCustomCaptureSoundPath);
FileHelpers.BrowseFile(txtCustomCaptureSoundPath);
}
private void cbUseCustomTaskCompletedSound_CheckedChanged(object sender, EventArgs e)
@ -898,7 +898,7 @@ private void txtCustomTaskCompletedSoundPath_TextChanged(object sender, EventArg
private void btnCustomTaskCompletedSoundPath_Click(object sender, EventArgs e)
{
Helpers.BrowseFile(txtCustomTaskCompletedSoundPath);
FileHelpers.BrowseFile(txtCustomTaskCompletedSoundPath);
}
private void cbUseCustomErrorSound_CheckedChanged(object sender, EventArgs e)
@ -914,7 +914,7 @@ private void txtCustomErrorSoundPath_TextChanged(object sender, EventArgs e)
private void btnCustomErrorSoundPath_Click(object sender, EventArgs e)
{
Helpers.BrowseFile(txtCustomErrorSoundPath);
FileHelpers.BrowseFile(txtCustomErrorSoundPath);
}
private void cbDisableNotifications_CheckedChanged(object sender, EventArgs e)

View file

@ -52,7 +52,7 @@ public WatchFolderForm(WatchFolderSettings watchFolder)
private void btnPathBrowse_Click(object sender, EventArgs e)
{
Helpers.BrowseFolder(txtFolderPath, "", true);
FileHelpers.BrowseFolder(txtFolderPath, "", true);
}
private void btnOK_Click(object sender, EventArgs e)

View file

@ -311,7 +311,7 @@ public static void CreateChromeExtensionSupport(bool create)
private static void CreateChromeHostManifest(string filePath)
{
Helpers.CreateDirectoryFromFilePath(filePath);
FileHelpers.CreateDirectoryFromFilePath(filePath);
ChromeManifest manifest = new ChromeManifest()
{
@ -381,7 +381,7 @@ public static void CreateFirefoxAddonSupport(bool create)
private static void CreateFirefoxHostManifest(string filePath)
{
Helpers.CreateDirectoryFromFilePath(filePath);
FileHelpers.CreateDirectoryFromFilePath(filePath);
FirefoxManifest manifest = new FirefoxManifest()
{
@ -437,7 +437,7 @@ public static void SteamShowInApp(bool showInApp)
{
if (showInApp)
{
Helpers.CreateEmptyFile(path);
FileHelpers.CreateEmptyFile(path);
}
else if (File.Exists(path))
{

View file

@ -135,13 +135,13 @@ public static string TitleShort
private const string PersonalPathConfigFileName = "PersonalPath.cfg";
public static readonly string DefaultPersonalFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Name);
public static readonly string PortablePersonalFolder = Helpers.GetAbsolutePath(Name);
public static readonly string PortablePersonalFolder = FileHelpers.GetAbsolutePath(Name);
private static string PersonalPathConfigFilePath
{
get
{
string relativePath = Helpers.GetAbsolutePath(PersonalPathConfigFileName);
string relativePath = FileHelpers.GetAbsolutePath(PersonalPathConfigFileName);
if (File.Exists(relativePath))
{
@ -157,9 +157,9 @@ private static string PersonalPathConfigFilePath
private static readonly string PreviousPersonalPathConfigFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
Name, PersonalPathConfigFileName);
private static readonly string PortableCheckFilePath = Helpers.GetAbsolutePath("Portable");
public static readonly string NativeMessagingHostFilePath = Helpers.GetAbsolutePath("ShareX_NativeMessagingHost.exe");
public static readonly string SteamInAppFilePath = Helpers.GetAbsolutePath("Steam");
private static readonly string PortableCheckFilePath = FileHelpers.GetAbsolutePath("Portable");
public static readonly string NativeMessagingHostFilePath = FileHelpers.GetAbsolutePath("ShareX_NativeMessagingHost.exe");
public static readonly string SteamInAppFilePath = FileHelpers.GetAbsolutePath("Steam");
private static string CustomPersonalPath { get; set; }
@ -169,7 +169,7 @@ public static string PersonalFolder
{
if (!string.IsNullOrEmpty(CustomPersonalPath))
{
return Helpers.ExpandFolderVariables(CustomPersonalPath);
return FileHelpers.ExpandFolderVariables(CustomPersonalPath);
}
return DefaultPersonalFolder;
@ -226,7 +226,7 @@ public static string ScreenshotsParentFolder
if (!string.IsNullOrEmpty(path))
{
path = Helpers.ExpandFolderVariables(path);
path = FileHelpers.ExpandFolderVariables(path);
if (string.IsNullOrEmpty(path2) || Directory.Exists(path))
{
@ -236,7 +236,7 @@ public static string ScreenshotsParentFolder
if (!string.IsNullOrEmpty(path2))
{
path2 = Helpers.ExpandFolderVariables(path2);
path2 = FileHelpers.ExpandFolderVariables(path2);
if (Directory.Exists(path2))
{
@ -469,7 +469,7 @@ private static void UpdatePersonalPath()
if (!string.IsNullOrEmpty(customPersonalPath))
{
CustomPersonalPath = Helpers.GetAbsolutePath(customPersonalPath);
CustomPersonalPath = FileHelpers.GetAbsolutePath(customPersonalPath);
PersonalPathDetectionMethod = $"PersonalPath.cfg file ({PersonalPathConfigFilePath})";
}
}
@ -506,11 +506,11 @@ private static void CreateParentFolders()
{
if (!Sandbox && Directory.Exists(PersonalFolder))
{
Helpers.CreateDirectory(SettingManager.BackupFolder);
Helpers.CreateDirectory(ImageEffectsFolder);
Helpers.CreateDirectory(LogsFolder);
Helpers.CreateDirectory(ScreenshotsParentFolder);
Helpers.CreateDirectory(ToolsFolder);
FileHelpers.CreateDirectory(SettingManager.BackupFolder);
FileHelpers.CreateDirectory(ImageEffectsFolder);
FileHelpers.CreateDirectory(LogsFolder);
FileHelpers.CreateDirectory(ScreenshotsParentFolder);
FileHelpers.CreateDirectory(ToolsFolder);
}
}
@ -547,7 +547,7 @@ private static void MigratePersonalPathConfig()
{
if (!File.Exists(CurrentPersonalPathConfigFilePath))
{
Helpers.CreateDirectoryFromFilePath(CurrentPersonalPathConfigFilePath);
FileHelpers.CreateDirectoryFromFilePath(CurrentPersonalPathConfigFilePath);
File.Move(PreviousPersonalPathConfigFilePath, CurrentPersonalPathConfigFilePath);
}
@ -592,7 +592,7 @@ public static bool WritePersonalPathConfig(string path)
{
try
{
Helpers.CreateDirectoryFromFilePath(PersonalPathConfigFilePath);
FileHelpers.CreateDirectoryFromFilePath(PersonalPathConfigFilePath);
File.WriteAllText(PersonalPathConfigFilePath, path, Encoding.UTF8);
return true;
}
@ -659,7 +659,7 @@ private static bool CheckUninstall()
private static bool CheckPuushMode()
{
string puushPath = Helpers.GetAbsolutePath("puush");
string puushPath = FileHelpers.GetAbsolutePath("puush");
PuushMode = File.Exists(puushPath);
return PuushMode;
}

View file

@ -47,7 +47,7 @@ public string FileName
text = URL;
}
return Helpers.GetFileNameSafe(text);
return FileHelpers.GetFileNameSafe(text);
}
}

View file

@ -301,7 +301,7 @@ private static void StartRecording(ScreenRecordOutput outputType, TaskSettings t
if (!currentFileName.Equals(customFileName, StringComparison.InvariantCultureIgnoreCase))
{
path = Helpers.RenameFile(path, customFileName + ext);
path = FileHelpers.RenameFile(path, customFileName + ext);
}
}

View file

@ -65,7 +65,7 @@ private static string UploadersConfigFilePath
if (Settings != null && !string.IsNullOrEmpty(Settings.CustomUploadersConfigPath))
{
uploadersConfigFolder = Helpers.ExpandFolderVariables(Settings.CustomUploadersConfigPath);
uploadersConfigFolder = FileHelpers.ExpandFolderVariables(Settings.CustomUploadersConfigPath);
}
else
{
@ -88,7 +88,7 @@ private static string HotkeysConfigFilePath
if (Settings != null && !string.IsNullOrEmpty(Settings.CustomHotkeysConfigPath))
{
hotkeysConfigFolder = Helpers.ExpandFolderVariables(Settings.CustomHotkeysConfigPath);
hotkeysConfigFolder = FileHelpers.ExpandFolderVariables(Settings.CustomHotkeysConfigPath);
}
else
{
@ -245,7 +245,7 @@ private static void MigrateHistoryFile()
}
}
Helpers.MoveFile(Program.HistoryFilePathOld, BackupFolder);
FileHelpers.MoveFile(Program.HistoryFilePathOld, BackupFolder);
}
}
@ -395,7 +395,7 @@ public static bool Import(string archivePath)
{
ZipManager.Extract(archivePath, Program.PersonalFolder, true, entry =>
{
return Helpers.CheckExtension(entry.Name, new string[] { "json", "xml" });
return FileHelpers.CheckExtension(entry.Name, new string[] { "json", "xml" });
}, 1_000_000_000);
return true;

View file

@ -483,7 +483,7 @@ public static string GetScreenshotsFolder(TaskSettings taskSettings = null, Task
screenshotsFolder = Path.Combine(Program.ScreenshotsParentFolder, subFolderPath);
}
return Helpers.GetAbsolutePath(screenshotsFolder);
return FileHelpers.GetAbsolutePath(screenshotsFolder);
}
public static bool ShowAfterCaptureForm(TaskSettings taskSettings, out string fileName, TaskMetadata metadata = null, string filePath = null)
@ -625,7 +625,7 @@ public static string HandleExistsFile(string filePath, TaskSettings taskSettings
}
break;
case FileExistAction.UniqueName:
filePath = Helpers.GetUniqueFilePath(filePath);
filePath = FileHelpers.GetUniqueFilePath(filePath);
break;
case FileExistAction.Cancel:
filePath = "";
@ -696,11 +696,11 @@ public static void OpenScreenshotsFolder()
if (Directory.Exists(screenshotsFolder))
{
Helpers.OpenFolder(screenshotsFolder);
FileHelpers.OpenFolder(screenshotsFolder);
}
else
{
Helpers.OpenFolder(Program.ScreenshotsParentFolder);
FileHelpers.OpenFolder(Program.ScreenshotsParentFolder);
}
}
@ -1302,12 +1302,12 @@ public static void TweetMessage()
public static EDataType FindDataType(string filePath, TaskSettings taskSettings)
{
if (Helpers.CheckExtension(filePath, taskSettings.AdvancedSettings.ImageExtensions))
if (FileHelpers.CheckExtension(filePath, taskSettings.AdvancedSettings.ImageExtensions))
{
return EDataType.Image;
}
if (Helpers.CheckExtension(filePath, taskSettings.AdvancedSettings.TextExtensions))
if (FileHelpers.CheckExtension(filePath, taskSettings.AdvancedSettings.TextExtensions))
{
return EDataType.Text;
}

View file

@ -497,8 +497,8 @@ public class TaskSettingsAdvanced
public TaskSettingsAdvanced()
{
this.ApplyDefaultPropertyValues();
ImageExtensions = Helpers.ImageFileExtensions.ToList();
TextExtensions = Helpers.TextFileExtensions.ToList();
ImageExtensions = FileHelpers.ImageFileExtensions.ToList();
TextExtensions = FileHelpers.TextFileExtensions.ToList();
}
}
}

View file

@ -115,17 +115,17 @@ public void OpenDeletionURL()
public void OpenFile()
{
if (IsItemSelected && SelectedItem.IsFileExist) Helpers.OpenFile(SelectedItem.Info.FilePath);
if (IsItemSelected && SelectedItem.IsFileExist) FileHelpers.OpenFile(SelectedItem.Info.FilePath);
}
public void OpenThumbnailFile()
{
if (IsItemSelected && SelectedItem.IsThumbnailFileExist) Helpers.OpenFile(SelectedItem.Info.ThumbnailFilePath);
if (IsItemSelected && SelectedItem.IsThumbnailFileExist) FileHelpers.OpenFile(SelectedItem.Info.ThumbnailFilePath);
}
public void OpenFolder()
{
if (IsItemSelected && SelectedItem.IsFileExist) Helpers.OpenFolderWithFile(SelectedItem.Info.FilePath);
if (IsItemSelected && SelectedItem.IsFileExist) FileHelpers.OpenFolderWithFile(SelectedItem.Info.FilePath);
}
public void TryOpen()
@ -144,7 +144,7 @@ public void TryOpen()
}
else if (SelectedItem.IsFilePathValid)
{
Helpers.OpenFile(SelectedItem.Info.FilePath);
FileHelpers.OpenFile(SelectedItem.Info.FilePath);
}
}
}
@ -353,7 +353,7 @@ public void DeleteFiles()
{
foreach (string filePath in SelectedItems.Select(x => x.Info.FilePath))
{
Helpers.DeleteFile(filePath, true);
FileHelpers.DeleteFile(filePath, true);
}
}
}

View file

@ -63,16 +63,16 @@ public void Update()
IsThumbnailURLExist = !string.IsNullOrEmpty(Info.Result.ThumbnailURL);
IsDeletionURLExist = !string.IsNullOrEmpty(Info.Result.DeletionURL);
IsFileURL = IsURLExist && URLHelpers.IsFileURL(Info.Result.URL);
IsImageURL = IsFileURL && Helpers.IsImageFile(Info.Result.URL);
IsTextURL = IsFileURL && Helpers.IsTextFile(Info.Result.URL);
IsImageURL = IsFileURL && FileHelpers.IsImageFile(Info.Result.URL);
IsTextURL = IsFileURL && FileHelpers.IsTextFile(Info.Result.URL);
}
IsFilePathValid = !string.IsNullOrEmpty(Info.FilePath) && Path.HasExtension(Info.FilePath);
IsFileExist = IsFilePathValid && File.Exists(Info.FilePath);
IsThumbnailFilePathValid = !string.IsNullOrEmpty(Info.ThumbnailFilePath) && Path.HasExtension(Info.ThumbnailFilePath);
IsThumbnailFileExist = IsThumbnailFilePathValid && File.Exists(Info.ThumbnailFilePath);
IsImageFile = IsFileExist && Helpers.IsImageFile(Info.FilePath);
IsTextFile = IsFileExist && Helpers.IsTextFile(Info.FilePath);
IsImageFile = IsFileExist && FileHelpers.IsImageFile(Info.FilePath);
IsTextFile = IsFileExist && FileHelpers.IsTextFile(Info.FilePath);
}
}
}

View file

@ -49,7 +49,8 @@ public virtual void Enable()
{
Dispose();
string folderPath = Helpers.ExpandFolderVariables(Settings.FolderPath);
string folderPath = FileHelpers.ExpandFolderVariables(Settings.FolderPath);
if (!string.IsNullOrEmpty(folderPath) && Directory.Exists(folderPath))
{
context = SynchronizationContext.Current ?? new SynchronizationContext();
@ -88,9 +89,9 @@ private async void fileWatcher_Created(object sender, FileSystemEventArgs e)
await Helpers.WaitWhileAsync(() =>
{
if (!Helpers.IsFileLocked(path))
if (!FileHelpers.IsFileLocked(path))
{
long currentSize = Helpers.GetFileSize(path);
long currentSize = FileHelpers.GetFileSize(path);
if (currentSize > 0 && currentSize == previousSize)
{

View file

@ -91,7 +91,7 @@ public void AddWatchFolder(WatchFolderSettings watchFolderSetting, TaskSettings
string screenshotsFolder = TaskHelpers.GetScreenshotsFolder(taskSettingsCopy);
string fileName = Path.GetFileName(origPath);
destPath = TaskHelpers.HandleExistsFile(screenshotsFolder, fileName, taskSettingsCopy);
Helpers.CreateDirectoryFromFilePath(destPath);
FileHelpers.CreateDirectoryFromFilePath(destPath);
File.Move(origPath, destPath);
}

View file

@ -107,7 +107,7 @@ public static WorkerTask CreateFileUploaderTask(string filePath, TaskSettings ta
if (task.Info.TaskSettings.UploadSettings.FileUploadUseNamePattern)
{
string ext = Helpers.GetFileNameExtension(task.Info.FilePath);
string ext = FileHelpers.GetFileNameExtension(task.Info.FilePath);
task.Info.FileName = TaskHelpers.GetFileName(task.Info.TaskSettings, ext);
}
@ -137,7 +137,7 @@ public static WorkerTask CreateImageUploaderTask(TaskMetadata metadata, TaskSett
if (!string.IsNullOrEmpty(customFileName))
{
task.Info.FileName = Helpers.AppendExtension(customFileName, "bmp");
task.Info.FileName = FileHelpers.AppendExtension(customFileName, "bmp");
}
else
{
@ -187,12 +187,12 @@ public static WorkerTask CreateFileJobTask(string filePath, TaskMetadata metadat
if (!string.IsNullOrEmpty(customFileName))
{
string ext = Helpers.GetFileNameExtension(task.Info.FilePath);
task.Info.FileName = Helpers.AppendExtension(customFileName, ext);
string ext = FileHelpers.GetFileNameExtension(task.Info.FilePath);
task.Info.FileName = FileHelpers.AppendExtension(customFileName, ext);
}
else if (task.Info.TaskSettings.UploadSettings.FileUploadUseNamePattern)
{
string ext = Helpers.GetFileNameExtension(task.Info.FilePath);
string ext = FileHelpers.GetFileNameExtension(task.Info.FilePath);
task.Info.FileName = TaskHelpers.GetFileName(task.Info.TaskSettings, ext);
}
@ -214,11 +214,11 @@ public static WorkerTask CreateDownloadTask(string url, bool upload, TaskSetting
string fileName = URLHelpers.URLDecode(url, 10);
fileName = URLHelpers.GetFileName(fileName);
fileName = Helpers.GetValidFileName(fileName);
fileName = FileHelpers.GetValidFileName(fileName);
if (task.Info.TaskSettings.UploadSettings.FileUploadUseNamePattern)
{
string ext = Helpers.GetFileNameExtension(fileName);
string ext = FileHelpers.GetFileNameExtension(fileName);
fileName = TaskHelpers.GetFileName(task.Info.TaskSettings, ext);
}
@ -763,8 +763,8 @@ private void DoFileJobs()
if (isFileModified)
{
string extension = Helpers.GetFileNameExtension(Info.FilePath);
Info.FileName = Helpers.ChangeFileNameExtension(fileName, extension);
string extension = FileHelpers.GetFileNameExtension(Info.FilePath);
Info.FileName = FileHelpers.ChangeFileNameExtension(fileName, extension);
LoadFileStream();
}
@ -782,7 +782,7 @@ private void DoFileJobs()
if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.ShowInExplorer))
{
Helpers.OpenFolderWithFile(Info.FilePath);
FileHelpers.OpenFolderWithFile(Info.FilePath);
}
if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.ScanQRCode) && Info.DataType == EDataType.Image)
@ -802,7 +802,7 @@ private void DoTextJobs()
if (!string.IsNullOrEmpty(filePath))
{
Info.FilePath = filePath;
Helpers.CreateDirectoryFromFilePath(Info.FilePath);
FileHelpers.CreateDirectoryFromFilePath(Info.FilePath);
File.WriteAllText(Info.FilePath, Text, Encoding.UTF8);
DebugHelper.WriteLine("Text saved to file: " + Info.FilePath);
}
@ -1056,7 +1056,7 @@ private bool DownloadFromURL(bool upload)
try
{
Helpers.CreateDirectoryFromFilePath(Info.FilePath);
FileHelpers.CreateDirectoryFromFilePath(Info.FilePath);
using (WebClient wc = new WebClient())
{