Here are the examples of the csharp api System.IO.FileInfo.MoveTo(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
126 Examples
19
Source : SftpWinForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void renameToolStripMenuItem_Click(object sender, EventArgs e)
{
int count = listView1.SelectedItems.Count;
if (count == 1)
{
ListViewItem item = listView1.SelectedItems[0];
Object tag = item.Tag;
string msg = "请输入文件夹的新名称";
if (tag is FileInfo)
{
msg = "请输入文件的新名称";
}
string oldName = item.Text;
InputForm form = new InputForm(msg, oldName, new InputForm.FormResult((newName) =>
{
if (oldName != newName)
{
string dirs = getCurrDir();
string path1 = dirs + oldName;
string path2 = dirs + newName;
if (tag is FileInfo)
{
FileInfo file = new FileInfo(path2);
if (!file.Exists)
{
new FileInfo(path1).MoveTo(path2);
}
}
else if (tag is DirectoryInfo)
{
DirectoryInfo dire = new DirectoryInfo(path2);
if (!dire.Exists)
{
new DirectoryInfo(path1).MoveTo(path2);
}
}
ThreadPool.QueueUserWorkItem((a) =>
{
Thread.Sleep(500);
RefreshFiles();
});
}
}));
form.ShowDialog(this);
}
}
19
Source : Utility.Http.cs
with MIT License
from 7Bytes-Studio
with MIT License
from 7Bytes-Studio
private void ReNameTempFile()
{
if (File.Exists(m_HttpDownloadInfo.SavePath + "." + m_HttpDownloadInfo.TempFileExtension))
{
if (File.Exists(m_HttpDownloadInfo.SavePath))
{
File.Delete(m_HttpDownloadInfo.SavePath);
}
FileInfo fileInfo = new FileInfo(m_HttpDownloadInfo.SavePath + "." + m_HttpDownloadInfo.TempFileExtension);
fileInfo.MoveTo(m_HttpDownloadInfo.SavePath);
//File.Move(m_HttpDownloadInfo.SavePath + m_HttpDownloadInfo.TempFileExtension, m_HttpDownloadInfo.SavePath);
}
}
19
Source : BuildProcessCallbacksHandler.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
private static void VerifyBuild( string targetDataPath )
{
var nativePluginsDirectory = new DirectoryInfo( AGXUnity.IO.Environment.GetPlayerPluginPath( targetDataPath ) );
if ( !nativePluginsDirectory.Exists ) {
Debug.LogWarning( "Build Warning: ".Color( Color.yellow ) +
nativePluginsDirectory.FullName +
" doesn't exist. " +
"This directory is where the AGX Dynamics binaries are expected to be located." );
return;
}
// It's not possible to use the PluginImporter during builds.
Predicate<FileInfo> isNativePlugin = fi => { return !fi.Name.ToLower().EndsWith( "dotnet.dll" ); };
var inProjectDllNames = new HashSet<string>( from dllFile
in new DirectoryInfo( IO.Utils.AGXUnityPluginDirectoryFull ).EnumerateFiles( "*.dll" )
where isNativePlugin( dllFile )
select dllFile.Name );
Func<bool> matchingNumProjectDllsWithBuild = () =>
{
var numMatchingDllsInBuild = nativePluginsDirectory.EnumerateFiles( "*.dll" ).Count( dllFi => inProjectDllNames.Contains( dllFi.Name ) );
// The dlls from the projects are all located in the
// expected nativePluginsDirectory.
return numMatchingDllsInBuild == inProjectDllNames.Count;
};
if ( matchingNumProjectDllsWithBuild() )
return;
// Check if the missing dlls are located in the parent
// directory of nativePluginsDirectory.
var nativePluginsParentDirectory = nativePluginsDirectory.Parent;
int numMoved = 0;
try {
foreach ( var dllFi in nativePluginsParentDirectory.EnumerateFiles( "*.dll" ) ) {
if ( !inProjectDllNames.Contains( dllFi.Name ) )
continue;
dllFi.MoveTo( nativePluginsDirectory.FullName +
Path.DirectorySeparatorChar +
dllFi.Name );
++numMoved;
}
}
catch ( Exception e ) {
Debug.LogException( e );
return;
}
if ( matchingNumProjectDllsWithBuild() ) {
Debug.Log( "Build info: ".Color( Color.green ) +
$"Successfully moved {numMoved} AGX Dynamics binaries to {nativePluginsDirectory.FullName.Replace( '\\', '/' )}" );
}
else {
Debug.LogWarning( "Build warning: ".Color( Color.yellow ) +
"AGX Dynamics binaries mismatch in build vs project. The application may not properly load AGX Dynamics." );
}
}
19
Source : Program.cs
with MIT License
from AmazingDM
with MIT License
from AmazingDM
private static void MoveDirectory(string sourceDirName, string destDirName, bool overwrite)
{
sourceDirName = Path.GetFullPath(sourceDirName);
destDirName = Path.GetFullPath(destDirName);
if (!overwrite)
{
Directory.Move(sourceDirName, destDirName);
}
else
{
var dirStack = new Stack<string>();
dirStack.Push(sourceDirName);
while (dirStack.Count > 0)
{
var dirInfo = new DirectoryInfo(dirStack.Pop());
try
{
foreach (var dirChildInfo in dirInfo.GetDirectories())
{
var destPath = dirChildInfo.FullName.Replace(sourceDirName, destDirName);
try
{
if (!Directory.Exists(destPath))
{
Directory.CreateDirectory(destPath);
}
}
catch (Exception e)
{
Console.WriteLine($"Create {destPath} Folder Error: {e.Message}");
}
dirStack.Push(dirChildInfo.FullName);
}
foreach (var fileChildInfo in dirInfo.GetFiles())
{
var destPath = fileChildInfo.FullName.Replace(sourceDirName, destDirName);
try
{
if (File.Exists(destPath))
{
File.Delete(destPath);
}
fileChildInfo.MoveTo(destPath);
}
catch (Exception e)
{
Console.WriteLine($"Move {fileChildInfo.FullName} To {destPath} Error: {e.Message}");
}
}
}
catch (Exception e)
{
Console.WriteLine($"ERROR:{e.Message}");
}
}
}
}
19
Source : UpdateHelper.cs
with MIT License
from AnnoDesigner
with MIT License
from AnnoDesigner
public async Task<string> DownloadReleaseAsync(AvailableRelease releaseToDownload)
{
try
{
if (AllReleases == null)
{
return null;
}
logger.Debug($"Download replacedet for release {releaseToDownload.Version}.");
var release = AllReleases.FirstOrDefault(x => x.Id == releaseToDownload.Id);
if (release == null)
{
logger.Warn($"No release found for {nameof(releaseToDownload.Id)}: {nameof(releaseToDownload.Id)}");
return null;
}
var replacedetName = GetreplacedetNameForReleaseType(releaseToDownload.Type);
if (string.IsNullOrWhiteSpace(replacedetName))
{
logger.Warn($"No replacedet name found for type: {releaseToDownload.Type}");
return null;
}
var foundreplacedet = release.replacedets.FirstOrDefault(x => x.Name.StartsWith(replacedetName, StringComparison.OrdinalIgnoreCase));
if (foundreplacedet == null && releaseToDownload.Type == ReleaseType.Presets)
{
//check for release of presets with icons
releaseToDownload.Type = ReleaseType.PresetsAndIcons;
replacedetName = GetreplacedetNameForReleaseType(releaseToDownload.Type);
foundreplacedet = release.replacedets.FirstOrDefault(x => x.Name.StartsWith(replacedetName, StringComparison.OrdinalIgnoreCase));
}
if (foundreplacedet == null)
{
logger.Warn($"No replacedet found with name: {replacedetName}");
return null;
}
//download file to temp directory
var pathToDownloadedFile = await DownloadFileAsync(foundreplacedet.BrowserDownloadUrl, Path.GetTempFileName()).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(pathToDownloadedFile))
{
logger.Warn("Could not get path to downloaded file.");
return null;
}
//move file to app directory
var tempFileInfo = new FileInfo(pathToDownloadedFile);
var pathToUpdatedPresetsFile = GetPathToUpdatedPresetsFile(releaseToDownload.Type);
if (string.IsNullOrWhiteSpace(pathToUpdatedPresetsFile))
{
logger.Warn($"Could not get path to updated presets file for type: {releaseToDownload.Type}");
return null;
}
if (File.Exists(pathToUpdatedPresetsFile))
{
FileHelper.ResetFileAttributes(pathToUpdatedPresetsFile);
File.Delete(pathToUpdatedPresetsFile);
}
tempFileInfo.MoveTo(pathToUpdatedPresetsFile);
return pathToUpdatedPresetsFile;
}
catch (Exception ex)
{
logger.Error(ex, "Error downloading release.");
App.ShowMessageWithUnexpectedError();
return null;
}
}
19
Source : ApiController.cs
with Apache License 2.0
from ant-design-blazor
with Apache License 2.0
from ant-design-blazor
[HttpPost("upload")]
public async Task<IActionResult> PostUrl()
{
if (Request.Content.IsMimeMultipartContent())
{
string root = System.IO.Path.Combine(Environment.CurrentDirectory, "wwwroot"); //<==Change Content Path
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);
Dictionary<string, string> dict = new Dictionary<string, string>(); //<==Use A dictionary To differ pictures in vditor upload
foreach (var file in provider.FileData)
{
string filename = file.Headers.ContentDisposition.FileName.Trim('"');
System.IO.FileInfo info = new System.IO.FileInfo(file.LocalFileName);
string savepath = System.IO.Path.Combine(root, filename);
if (!System.IO.File.Exists(savepath))
{
//<== Skip File If Exists
info.MoveTo(savepath);
}
dict.Add(filename, "api/image/" + filename);
}
return new JsonResult(new
{
Msg = "",
Code = 0,
Data = new { SuccMap = dict }
});
}
return new JsonResult(new
{
Msg = "错误",
Code = -1000,
Data = new { }
});
}
19
Source : FileInfoExtensions.cs
with GNU General Public License v3.0
from Artentus
with GNU General Public License v3.0
from Artentus
public static async Task<FileInfo> MoveToAsync(this FileInfo file, string path)
{
var root1 = Path.GetPathRoot(file.FullName);
var root2 = Path.GetPathRoot(path);
if (string.Equals(root1, root2, StringComparison.OrdinalIgnoreCase)) // Moving to same drive is almost instant
{
var newFile = new FileInfo(path);
if (!newFile.Directory.Exists) newFile.Directory.Create();
file.MoveTo(newFile.FullName);
return newFile;
}
else // Moving to different drive is a copy then delete
{
var newFile = await CopyToAsync(file, path);
file.Delete();
return newFile;
}
}
19
Source : FileInfoExtensions.cs
with GNU General Public License v3.0
from Artentus
with GNU General Public License v3.0
from Artentus
public static void Rename(this FileInfo file, string newName) => file.MoveTo(Path.Combine(file.Directory.FullName, newName));
19
Source : FileInfoExtensions.cs
with GNU General Public License v3.0
from Artentus
with GNU General Public License v3.0
from Artentus
public static async ValueTask MoveToAsync(this FileInfo file, string destination, bool overwrite = false)
{
if (FileHelper.IsOnSameVolume(file.FullName, destination))
{
// Moving to the same volume is fast, so we don't need to await it
file.MoveTo(destination);
}
else
{
await Task.Run(() => file.MoveTo(destination, overwrite));
}
}
19
Source : FileInfoExtensions.cs
with GNU General Public License v3.0
from Artentus
with GNU General Public License v3.0
from Artentus
public static async ValueTask MoveToAsync(this FileInfo file, string destination, bool overwrite = false)
{
if (FileHelper.IsOnSameVolume(file.FullName, destination))
{
// Moving to the same volume is fast, so we don't need to await it
file.MoveTo(destination);
}
else
{
await Task.Run(() => file.MoveTo(destination, overwrite));
}
}
19
Source : FileInfoExtensions.cs
with GNU General Public License v3.0
from Artentus
with GNU General Public License v3.0
from Artentus
public static void Rename(this FileInfo file, string newName)
=> file.MoveTo(Path.Combine(file.Directory!.FullName, newName));
19
Source : NetworkCache.cs
with Apache License 2.0
from ascora
with Apache License 2.0
from ascora
internal Task RenameTempFileAsync(FileExtension extension, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.Run(() =>
{
string fileName = FilenameForUrl(_url, extension, true);
var file = new System.IO.FileInfo(fileName);
string newFileName = file.Name.Replace(".temp", "");
string oldFilename = file.Name;
try
{
file.MoveTo(newFileName);
Debug.WriteLine($"Copying temp file to real file ({file.Name})", LottieLog.Tag);
}
catch
{
LottieLog.Warn($"Unable to rename cache file {oldFilename} to {newFileName}.");
}
});
}
19
Source : Program.cs
with GNU General Public License v3.0
from AutoDarkMode
with GNU General Public License v3.0
from AutoDarkMode
private static void MoveToTemp()
{
// collect all files that are not within the update data directory or the updater itself and the ignore list
IEnumerable<string> oldFilePaths = Directory.EnumerateFileSystemEntries(Extensions.ExecutionDir, "*.*", SearchOption.TopDirectoryOnly)
.Where(f => !f.Contains(Extensions.UpdateDataDir) && !f.Contains(Extensions.ExecutionDirUpdater) && !IgnorePaths(f));
//this operation is dangerous if in the wrong directory, ensure that the AutoDarkModeSvc.exe is in the same directory
if (!oldFilePaths.Contains(Extensions.ExecutionPathSvc))
{
Logger.Error($"patching aborted, wrong directory / service executable not found {Extensions.ExecutionPathSvc}");
Relaunch(restoreShell, restoreApp, true);
Environment.Exit(-1);
}
Logger.Info("backing up old files");
// convert to file info list and move all files into a demporary directory that is a sub directory of the update data dir
// this is done so the dir can be removed easily once the update is complete
try
{
if (!Directory.Exists(holdingDir))
{
Directory.CreateDirectory(holdingDir);
}
foreach (string path in oldFilePaths)
{
if (File.Exists(path))
{
FileInfo file = new(path);
string targetPath = Path.Combine(holdingDir, Path.GetRelativePath(Extensions.ExecutionDir, file.FullName));
file.MoveTo(targetPath, true);
}
else if (Directory.Exists(path))
{
DirectoryInfo dir = new(path);
string targetPath = Path.Combine(holdingDir, Path.GetRelativePath(Extensions.ExecutionDir, dir.FullName));
dir.MoveTo(targetPath);
}
//Logger.Info($"moved file {file.Name} to holding dir");
}
}
catch (Exception ex)
{
Logger.Error(ex, "could not move all files to holding dir, attempting rollback:");
RollbackDir(holdingDir, Extensions.ExecutionDir);
Cleanup();
Relaunch(restoreShell, restoreApp, true);
Environment.Exit(-1);
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from AutoDarkMode
with GNU General Public License v3.0
from AutoDarkMode
private static void CopyNewFiles()
{
Logger.Info("patching auto dark mode");
// move new files from unpack directory to replacedembly path
string unpackDirectory = Path.Combine(Extensions.UpdateDataDir, "unpacked");
IEnumerable<string> paths = Directory.EnumerateFileSystemEntries(unpackDirectory, "*.*", SearchOption.TopDirectoryOnly);
try
{
foreach (string path in paths)
{
if (File.Exists(path))
{
FileInfo file = new(path);
string targetPath = Path.Combine(Extensions.ExecutionDir, Path.GetRelativePath(unpackDirectory, file.FullName));
file.MoveTo(targetPath, true);
}
else if (Directory.Exists(path))
{
DirectoryInfo dir = new(path);
string targetPath = Path.Combine(Extensions.ExecutionDir, Path.GetRelativePath(unpackDirectory, dir.FullName));
dir.MoveTo(targetPath);
}
}
}
catch (Exception ex)
{
Logger.Error(ex, "could not move all files, attempting rollback:");
RollbackDir(holdingDir, Extensions.ExecutionDir);
Cleanup();
Relaunch(restoreShell, restoreApp, true);
Environment.Exit(-1);
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from AutoDarkMode
with GNU General Public License v3.0
from AutoDarkMode
private static void RollbackDir(string source, string target)
{
try
{
PrepareRollback();
IEnumerable<string> holdingPaths = Directory.EnumerateFileSystemEntries(source, "*.*", SearchOption.TopDirectoryOnly);
foreach (var path in holdingPaths)
{
if (File.Exists(path))
{
FileInfo file = new(path);
string targetPath = Path.Combine(target, Path.GetRelativePath(source, file.FullName));
file.MoveTo(targetPath, true);
Logger.Info($"rolled back file {file.Name} to default dir {target}");
}
else if (Directory.Exists(path))
{
DirectoryInfo dir = new(path);
string targetPath = Path.Combine(target, Path.GetRelativePath(source, dir.FullName));
dir.MoveTo(targetPath);
Logger.Info($"rolled back directory {dir.Name} to {targetPath}");
}
}
}
catch (Exception ex)
{
Logger.Fatal(ex, "rollback failed, this is non-recoverable, please reinstall auto dark mode:");
Environment.Exit(-2);
}
Logger.Info("rollback successful, no update has been performed, restarting auto dark mode");
}
19
Source : ForumTemplate.cs
with GNU General Public License v2.0
from BlackTasty
with GNU General Public License v2.0
from BlackTasty
public void Rename(string newName)
{
if (!Name.Equals(newName))
{
fileInfo?.MoveTo(fileInfo.DirectoryName + "\\" + newName + fileInfo.Extension);
}
}
19
Source : MainSvc.cs
with GNU General Public License v3.0
from bp2008
with GNU General Public License v3.0
from bp2008
private void UpdateWatch()
{
try
{
try
{
Process.GetCurrentProcess().PriorityClreplaced = ProcessPriorityClreplaced.AboveNormal;
}
catch (ThreadAbortException) { throw; }
catch { }
Try.Swallow(() => { BiUserInfo.CreateTemporaryUser(); });
cpuCounterTotal = new PerformanceCounter("Processor", "% Processor Time", "_Total");
interruptCounterTotal = new PerformanceCounter("Processor", "% Interrupt Time", "_Total");
DateTime lastDailyRegistryBackup = DateTime.MinValue;
while (true)
{
Thread.Sleep(1500);
Verbose("Starting Iteration");
try
{
PerformanceDataCollector.HandlePossiblePerfDataReport(Program.settings.lastUsageReportAt);
DateTime now = DateTime.Now;
if (lastDailyRegistryBackup.Year != now.Year || lastDailyRegistryBackup.Month != now.Month || lastDailyRegistryBackup.Day != now.Day)
{
lastDailyRegistryBackup = now;
if (Program.settings.dailyRegistryBackups)
RegistryBackup.BackupNow(Program.settings.GetDailyRegistryBackupLocation() + Path.DirectorySeparatorChar + "BI_REG_" + DateTime.Now.ToString("yyyy-MM-dd") + ".reg",
Program.settings.bi32OnWin64);
}
// Build a list of unique directories that have an active blueiris.exe.
// There is not likely to be more than one directory, though a single directory
// can easily have two blueiris.exe (service and GUI).
List<BiUpdateMapping> biUpdateMap = GetUpdateInfo();
if (biUpdateMap.Count == 0)
{
Verbose("No Blue Iris processes detected");
}
else
{
foreach (BiUpdateMapping mapping in biUpdateMap)
{
if (mapping.updateProcs.Length > 0)
{
// Blue Iris is currently being updated. Kill the blueiris.exe processes if configured to do so.
Logger.Info("Blue Iris update detected in path: " + mapping.dirPath);
if (Program.settings.includeRegistryWithUpdateBackup)
{
BiVersionInfo versionInfo = GetBiVersionInfo(mapping);
TryBackupRegistryForBiVersion(versionInfo);
}
if (Program.settings.killBlueIrisProcessesDuringUpdate2)
{
Logger.Info("Killing " + mapping.GetNumProcsLabel());
mapping.KillBiProcs();
}
Verbose("Waiting for update to complete");
mapping.WaitUntilUpdateProcsStop(TimeSpan.FromMinutes(5));
}
else
{
// Blue Iris is not being updated in this directory.
if (Program.settings.killBlueIrisProcessesDuringUpdate2 && (blueIrisServiceStopping || systemInFrozenState))
{
mapping.KillBiProcs();
if (blueIrisServiceStopping)
Logger.Info("Blue Iris service found in stopping state. Killed " + mapping.GetNumProcsLabel());
else if (systemInFrozenState)
Logger.Info("System freeze with high interrupt % detected. Killed " + mapping.GetNumProcsLabel());
continue;
}
// Back up the update file if configured to do so.
if (!Program.settings.backupUpdateFiles)
continue;
//Check for the existence of an update.exe file
FileInfo fiUpdate = new FileInfo(GetUpdateDir5_1() + "update.exe");
if (!fiUpdate.Exists)
{
Verbose("No update file to back up in path: " + fiUpdate.DirectoryName);
fiUpdate = new FileInfo(mapping.dirPath + "update.exe");
}
if (!fiUpdate.Exists)
{
Verbose("No update file to back up in path: " + fiUpdate.DirectoryName);
continue;
}
Verbose("Backing up update file: " + fiUpdate.FullName);
// Get Blue Iris process(es) (necessary to learn if it is 64 or 32 bit)
BiVersionInfo versionInfo = GetBiVersionInfo(mapping);
if (versionInfo == null)
continue; // BI is probably not running
string blueIrisFolderPath = Program.settings.GetUpdateBackupLocation(mapping.dirPath);
FileInfo targetUpdateFile = new FileInfo(Path.Combine(blueIrisFolderPath, "update" + versionInfo.cpu_32_64 + "_" + versionInfo.version + ".exe"));
if (targetUpdateFile.Exists)
{
// A backed-up update file for the active Blue Iris version already exists, so we should do nothing now
Verbose("Target update file \"" + targetUpdateFile.FullName + "\" already exists. Probably, the new update file hasn't been installed yet.");
TryBackupRegistryForBiVersion(versionInfo);
}
else
{
// Find out if the file can be opened exclusively (meaning it is finished downloading, etc)
bool fileIsUnlocked = false;
try
{
using (FileStream fs = new FileStream(fiUpdate.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
fileIsUnlocked = true;
}
}
catch (ThreadAbortException) { throw; }
catch (Exception) { }
if (fileIsUnlocked)
{
// This is a pretty good sign that the update is not curently being installed, so we should be safe to rename the update file.
Logger.Info("Renaming update file to: " + targetUpdateFile.FullName);
fiUpdate.MoveTo(targetUpdateFile.FullName);
}
else
Verbose("Update file could not be exclusively locked. Backup will not occur this iteration.");
}
}
}
}
}
catch (ThreadAbortException) { throw; }
catch (Exception ex)
{
Logger.Debug(ex);
}
}
}
catch (ThreadAbortException) { }
catch (Exception ex)
{
Logger.Debug(ex);
}
}
19
Source : FileExtensions.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
public static bool MoveToV2(this FileInfo self, DirectoryInfo target) {
self.MoveTo(target.FullPath() + self.Name);
target.Refresh();
return self.ExistsV2();
}
19
Source : FileExtensions.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
public static bool Rename(this FileInfo self, string newName) {
self.MoveTo(self.ParentDir().GetChild(newName).FullPath());
return self.ExistsV2();
}
19
Source : Program.cs
with GNU General Public License v3.0
from cryptoprofitswitcher
with GNU General Public License v3.0
from cryptoprofitswitcher
private static void InitLogging()
{
WriteInfo(" Initialize logging..");
string logPath = Path.Combine(AppFolderPath, "current_log.txt");
try
{
var logFile = new FileInfo(logPath);
if (logFile.Exists)
{
string oldlogPath = Path.Combine(AppFolderPath, "previous_log.txt");
if (File.Exists(oldlogPath))
{
File.Delete(oldlogPath);
}
logFile.MoveTo(oldlogPath);
}
}
catch (Exception e)
{
Console.WriteLine(" Couldn't initalize logging " + e.Message);
}
if (Config.EnableLogging)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(LogEventLevel.Information)
.WriteTo.File(logPath)
.CreateLogger();
}
else
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(LogEventLevel.Information)
.CreateLogger();
}
}
19
Source : CodeGenerator.cs
with MIT License
from CslaGenFork
with MIT License
from CslaGenFork
private void GenerateObject(CslaObjectInfo objInfo, CslaGeneratorUnit unit)
{
Metadata.GenerationParameters generationParams = unit.GenerationParams;
string fileName = GetFileName(objInfo, generationParams.SeparateNamespaces, generationParams.OutputLanguage);
string baseFileName = GetBaseFileName(objInfo, generationParams.SeparateBaseClreplacedes, generationParams.SeparateNamespaces, generationParams.UseDotDesignerFileNameConvention, generationParams.OutputLanguage);
try
{
GenerateInheritanceFile(fileName, objInfo, generationParams.ActiveObjects, unit);
string tPath = this._fullTemplatesPath + generationParams.OutputLanguage.ToString() + @"\" + GetTemplateName(objInfo);
CodeTemplate template = GetTemplate(objInfo, tPath);
if (template != null)
{
StringBuilder errorsOutput = new StringBuilder();
StringBuilder warningsOutput = new StringBuilder();
template.SetProperty("ActiveObjects", generationParams.ActiveObjects);
template.SetProperty("Errors", errorsOutput);
template.SetProperty("Warnings", warningsOutput);
template.SetProperty("CurrentUnit", unit);
template.SetProperty("DataSetLoadingScheme", objInfo.DataSetLoadingScheme);
if (generationParams.BackupOldSource && File.Exists(baseFileName))
{
FileInfo oldFile = new FileInfo(baseFileName);
if (File.Exists(baseFileName + ".old"))
{
File.Delete(baseFileName + ".old");
}
oldFile.MoveTo(baseFileName + ".old");
}
FileInfo fi = new FileInfo(baseFileName);
using (FileStream fs = fi.Open(FileMode.Create))
{
OnGenerationFileName(fi.FullName);
using (StreamWriter swBase = new StreamWriter(fs))
{
template.Render(swBase);
errorsOutput = (StringBuilder)template.GetProperty("Errors");
warningsOutput = (StringBuilder)template.GetProperty("Warnings");
if (errorsOutput.Length > 0)
{
objFailed++;
OnGenerationInformation("Failed:" + Environment.NewLine +
errorsOutput.ToString(), 2);
}
else
{
if (warningsOutput != null)
{
if (warningsOutput.Length > 0)
{
objectWarnings++;
OnGenerationInformation("Warning:" + Environment.NewLine + warningsOutput, 2);
}
}
objSuccess++;
}
}
}
}
}
catch (Exception e)
{
objFailed++;
ShowExceptionInformation(e);
}
}
19
Source : CodeGenerator.cs
with MIT License
from CslaGenFork
with MIT License
from CslaGenFork
private void GenerateObject(CslaObjectInfo objInfo, CslaGeneratorUnit unit)
{
Metadata.GenerationParameters generationParams = unit.GenerationParams;
string fileName = GetBaseFileName(objInfo, false, generationParams.SeparateBaseClreplacedes, generationParams.SeparateNamespaces, generationParams.BaseFilenameSuffix, generationParams.ExtendedFilenameSuffix, generationParams.ClreplacedCommentFilenameSuffix, false, false);
string baseFileName = GetBaseFileName(objInfo, true, generationParams.SeparateBaseClreplacedes, generationParams.SeparateNamespaces, generationParams.BaseFilenameSuffix, generationParams.ExtendedFilenameSuffix, generationParams.ClreplacedCommentFilenameSuffix, false, false);
string clreplacedCommentFileName = string.Empty;
if (!string.IsNullOrEmpty(generationParams.ClreplacedCommentFilenameSuffix))
clreplacedCommentFileName = GetBaseFileName(objInfo, false, generationParams.SeparateBaseClreplacedes, generationParams.SeparateNamespaces, generationParams.BaseFilenameSuffix, generationParams.ExtendedFilenameSuffix, generationParams.ClreplacedCommentFilenameSuffix, true, generationParams.SeparateClreplacedComment);
FileStream fsBase = null;
StreamWriter swBase = null;
StreamWriter sw = null;
try
{
string tPath = this._fullTemplatesPath + objInfo.OutputLanguage.ToString() + @"\" + GetTemplateName(objInfo);
CodeTemplate template = GetTemplate(objInfo, tPath);
if (template != null)
{
StringBuilder errorsOutput = new StringBuilder();
StringBuilder warningsOutput = new StringBuilder();
template.SetProperty("ActiveObjects", generationParams.ActiveObjects);
template.SetProperty("Errors", errorsOutput);
template.SetProperty("Warnings", warningsOutput);
template.SetProperty("CurrentUnit", unit);
template.SetProperty("DataSetLoadingScheme", objInfo.DataSetLoadingScheme);
if (generationParams.BackupOldSource && File.Exists(baseFileName))
{
FileInfo oldFile = new FileInfo(baseFileName);
if (File.Exists(baseFileName + ".old"))
{
File.Delete(baseFileName + ".old");
}
oldFile.MoveTo(baseFileName + ".old");
}
fsBase = File.Open(baseFileName, FileMode.Create);
OnGenerationFileName(baseFileName);
swBase = new StreamWriter(fsBase);
template.Render(swBase);
errorsOutput = (StringBuilder)template.GetProperty("Errors");
warningsOutput = (StringBuilder)template.GetProperty("Warnings");
if (errorsOutput.Length > 0)
{
objFailed++;
OnGenerationInformation("Failed:" + Environment.NewLine + errorsOutput);
}
else
{
if (warningsOutput != null)
{
if (warningsOutput.Length > 0)
{
objectWarnings++;
OnGenerationInformation("Warning:" + Environment.NewLine + warningsOutput);
}
}
objSuccess++;
//OnGenerationInformation("Success");
}
}
GenerateInheritanceFile(fileName, objInfo, generationParams.ActiveObjects, unit);
if (!string.IsNullOrEmpty(generationParams.ClreplacedCommentFilenameSuffix))
GenerateClreplacedCommentFile(clreplacedCommentFileName, objInfo, generationParams.ActiveObjects, unit);
}
catch (Exception e)
{
objFailed++;
ShowExceptionInformation(e);
}
finally
{
if (sw != null)
{
sw.Close();
}
if (swBase != null)
{
swBase.Close();
}
}
}
19
Source : MyDataHelper.cs
with MIT License
from dimojang
with MIT License
from dimojang
public static void RenameFile(string srcFile, string destFile)
{
FileInfo fi = new FileInfo(srcFile); //xx/xx/aa.rar
if(File.Exists(destFile))
File.Copy(destFile, destFile + ".bak");
if(File.Exists(destFile)) File.Delete(destFile);
fi.MoveTo(destFile); //xx/xx/xx.rar
File.Delete(destFile + ".bak");
}
19
Source : UtilJsonTests.cs
with MIT License
from DjvuNet
with MIT License
from DjvuNet
[Fact]
public void BuildRequiredTest001()
{
FileInfo hashFileInfo = new FileInfo(HashFilePath);
if (hashFileInfo.Exists)
{
string backupHashFile = HashFilePath + ".bak";
if (File.Exists(backupHashFile))
File.Delete(backupHashFile);
try
{
hashFileInfo.MoveTo(backupHashFile);
CalculateHashes = false;
UtilJson.ArtifactsBuildRequired(ArtifactsDirectory, ArtifactsSearchPattern, SubdirectoryList,
SubdirectorySearchPatterns, HashFilePath, out CalculateHashes);
replacedert.True(CalculateHashes);
}
finally
{
if (File.Exists(backupHashFile))
{
if (!File.Exists(HashFilePath))
File.Move(backupHashFile, HashFilePath);
else
File.Delete(backupHashFile);
}
}
}
}
19
Source : FileInfoExtensions.cs
with MIT License
from dotnet-toolbelt
with MIT License
from dotnet-toolbelt
public static void MoveTo(this FileInfo fileInfo, string destFileName, bool renameWhenExists = false)
{
string newFullPath = string.Empty;
if (renameWhenExists)
{
int count = 1;
string fileNameOnly = Path.GetFileNameWithoutExtension(fileInfo.FullName);
string extension = Path.GetExtension(fileInfo.FullName);
newFullPath = Path.Combine(destFileName, fileInfo.Name);
while (File.Exists(newFullPath))
{
string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
newFullPath = Path.Combine(destFileName, tempFileName + extension);
}
}
fileInfo.MoveTo(renameWhenExists ? newFullPath : destFileName);
}
19
Source : FileInfoExtensions.cs
with MIT License
from dotnet-toolbelt
with MIT License
from dotnet-toolbelt
public static void Rename(this FileInfo @this, string newName)
{
string filePath = Path.Combine(@this.Directory?.FullName ?? throw new InvalidOperationException(), newName);
@this.MoveTo(filePath);
}
19
Source : FileInfoExtensions.cs
with MIT License
from dotnet-toolbelt
with MIT License
from dotnet-toolbelt
public static void RenameExtension(this FileInfo @this, string extension)
{
string filePath = Path.ChangeExtension(@this.FullName, extension);
@this.MoveTo(filePath);
}
19
Source : FileInfoExtensions.cs
with MIT License
from dotnet-toolbelt
with MIT License
from dotnet-toolbelt
public static void RenameFileWithoutExtension(this FileInfo @this, string newName)
{
string fileName = string.Concat(newName, @this.Extension);
string filePath = Path.Combine(@this.Directory?.FullName ?? throw new InvalidOperationException(), fileName);
@this.MoveTo(filePath);
}
19
Source : SystemInteractions.cs
with GNU General Public License v3.0
from easly1989
with GNU General Public License v3.0
from easly1989
public static string RenameFile(string fullPath, string newName = "")
{
var file = new FileInfo(fullPath);
if (!file.Exists)
return string.Empty;
if (string.IsNullOrWhiteSpace(newName))
{
var split = file.Name.Split(new[] { '.' }, 2, StringSplitOptions.RemoveEmptyEntries);
newName = $"{split[0]}.{DateTime.Now.Ticks}.{split[1]}";
}
try
{
// if the File.Exists than it is not possible that the Directory doesn't!
// ReSharper disable PossibleNullReferenceException
var newPath = Path.Combine(file.Directory.FullName, newName);
// ReSharper restore PossibleNullReferenceException
file.MoveTo(newPath);
return newPath;
}
catch (Exception)
{
return fullPath;
}
}
19
Source : DataStore.cs
with MIT License
from ekblom
with MIT License
from ekblom
public void MoveNote(Note note, Notebook notebook)
{
var oldNotebook = note.Notebook;
var filePath = GetNoteFilePath(note);
var fi = new FileInfo(filePath);
DisableWatcher();
//NOTE: Move files before updating notebook id since nf.FullName uses that.
var noteFolder = GetNotebookFolderPath(notebook.ID);
foreach (var nf in note.Files)
{
var noteFile = new FileInfo(nf.FullName);
if (noteFile.Exists)
noteFile.MoveTo(string.Join("\\", noteFolder, nf.FileName));
}
note.Notebook = notebook.ID;
filePath = GetNoteFilePath(note);
fi.MoveTo(filePath);
EnableWatcher();
SaveNote(note, true);
foreach (var cachItem in _cache)
if (cachItem.Key.ID == oldNotebook)
{
cachItem.Value.Remove(note);
break;
}
_cache[notebook].Add(note);
}
19
Source : Library.cs
with MIT License
from ekblom
with MIT License
from ekblom
private void RenameFile(string from, string to)
{
var fileName = GetFileName(from);
var toFileName = GetFileName(to);
if (File.Exists(fileName) && !File.Exists(toFileName))
{
var fi = new FileInfo(fileName);
fi.MoveTo(toFileName);
return;
}
if (File.Exists(fileName))
throw new LibraryExistsException();
}
19
Source : DirectoryUtilities.cs
with MIT License
from exyl-exe
with MIT License
from exyl-exe
private static void moveFiles(string sourceDirName, string destDirName)
{
if (!Directory.Exists(sourceDirName) || !Directory.Exists(destDirName)) return;
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string tempPath = Path.Combine(destDirName, file.Name);
if (!File.Exists(tempPath))
{
file.MoveTo(tempPath);
}
else
{
var i = 1;
string renamedFilePath;
do
{
renamedFilePath = string.Format("{0}{1}", tempPath, i);
i++;
} while (File.Exists(renamedFilePath));
file.CopyTo(renamedFilePath, false);
}
}
}
19
Source : TestProjectDuplicator.cs
with GNU General Public License v3.0
from Faultify
with GNU General Public License v3.0
from Faultify
public List<TestProjectDuplication> MakeInitialCopies(IProjectInfo testProject, int count)
{
var dirInfo = new DirectoryInfo(_testDirectory);
// Remove useless folders.
foreach (var directory in dirInfo.GetDirectories("*"))
{
var match = Regex.Match(directory.Name,
"(^cs$|^pl$|^rt$|^de$|^en$|^es$|^fr$|^it$|^ja$|^ko$|^ru$|^zh-Hans$|^zh-Hant$|^test-duplication-\\d$)");
if (match.Captures.Count != 0) Directory.Delete(directory.FullName, true);
}
var testProjectDuplications = new List<TestProjectDuplication>();
// Start the initial copy
var allFiles = Directory.GetFiles(_testDirectory, "*.*", SearchOption.AllDirectories).ToList();
var newDirInfo = Directory.CreateDirectory(Path.Combine(_testDirectory, "test-duplication-0"));
foreach (var file in allFiles)
try
{
var mFile = new FileInfo(file);
if (mFile.Directory.FullName == newDirInfo.Parent.FullName)
{
var newPath = Path.Combine(newDirInfo.FullName, mFile.Name);
mFile.MoveTo(newPath);
}
else
{
var path = mFile.FullName.Replace(newDirInfo.Parent.FullName, "");
var newPath = new FileInfo(Path.Combine(newDirInfo.FullName, path.Trim('\\')));
if (!Directory.Exists(newPath.DirectoryName)) Directory.CreateDirectory(newPath.DirectoryName);
mFile.MoveTo(newPath.FullName, true);
}
}
catch (Exception e)
{
throw e;
}
var initialCopies = testProject.ProjectReferences
.Select(x => new FileDuplication(newDirInfo.FullName, Path.GetFileNameWithoutExtension(x) + ".dll"));
testProjectDuplications.Add(new TestProjectDuplication(
new FileDuplication(newDirInfo.FullName, Path.GetFileName(testProject.replacedemblyPath)),
initialCopies,
0
));
// Copy the initial copy N times.
Parallel.ForEach(Enumerable.Range(1, count), i =>
{
var duplicatedDirectoryPath = Path.Combine(_testDirectory, $"test-duplication-{i}");
CopyFilesRecursively(newDirInfo, Directory.CreateDirectory(duplicatedDirectoryPath));
var duplicatedreplacedeblies = testProject.ProjectReferences
.Select(x =>
new FileDuplication(duplicatedDirectoryPath, Path.GetFileNameWithoutExtension(x) + ".dll"));
testProjectDuplications.Add(
new TestProjectDuplication(
new FileDuplication(duplicatedDirectoryPath, Path.GetFileName(testProject.replacedemblyPath)),
duplicatedreplacedeblies,
i
)
);
});
return testProjectDuplications;
}
19
Source : TestProjectDuplicator.cs
with GNU General Public License v3.0
from Faultify
with GNU General Public License v3.0
from Faultify
public List<TestProjectDuplication> MakeInitialCopies(IProjectInfo testProject, int count)
{
var dirInfo = new DirectoryInfo(_testDirectory);
// Remove useless folders.
foreach (var directory in dirInfo.GetDirectories("*"))
{
var match = Regex.Match(directory.Name,
"(^cs$|^pl$|^rt$|^de$|^en$|^es$|^fr$|^it$|^ja$|^ko$|^ru$|^zh-Hans$|^zh-Hant$|^test-duplication-\\d$)");
if (match.Captures.Count != 0) Directory.Delete(directory.FullName, true);
}
var testProjectDuplications = new List<TestProjectDuplication>();
// Start the initial copy
var allFiles = Directory.GetFiles(_testDirectory, "*.*", SearchOption.AllDirectories).ToList();
var newDirInfo = Directory.CreateDirectory(Path.Combine(_testDirectory, "test-duplication-0"));
foreach (var file in allFiles)
try
{
var mFile = new FileInfo(file);
if (mFile.Directory.FullName == newDirInfo.Parent.FullName)
{
var newPath = Path.Combine(newDirInfo.FullName, mFile.Name);
mFile.MoveTo(newPath);
}
else
{
var path = mFile.FullName.Replace(newDirInfo.Parent.FullName, "");
var newPath = new FileInfo(Path.Combine(newDirInfo.FullName, path.Trim('\\')));
if (!Directory.Exists(newPath.DirectoryName)) Directory.CreateDirectory(newPath.DirectoryName);
mFile.MoveTo(newPath.FullName, true);
}
}
catch (Exception e)
{
throw e;
}
var initialCopies = testProject.ProjectReferences
.Select(x => new FileDuplication(newDirInfo.FullName, Path.GetFileNameWithoutExtension(x) + ".dll"));
testProjectDuplications.Add(new TestProjectDuplication(
new FileDuplication(newDirInfo.FullName, Path.GetFileName(testProject.replacedemblyPath)),
initialCopies,
0
));
// Copy the initial copy N times.
Parallel.ForEach(Enumerable.Range(1, count), i =>
{
var duplicatedDirectoryPath = Path.Combine(_testDirectory, $"test-duplication-{i}");
CopyFilesRecursively(newDirInfo, Directory.CreateDirectory(duplicatedDirectoryPath));
var duplicatedreplacedeblies = testProject.ProjectReferences
.Select(x =>
new FileDuplication(duplicatedDirectoryPath, Path.GetFileNameWithoutExtension(x) + ".dll"));
testProjectDuplications.Add(
new TestProjectDuplication(
new FileDuplication(duplicatedDirectoryPath, Path.GetFileName(testProject.replacedemblyPath)),
duplicatedreplacedeblies,
i
)
);
});
return testProjectDuplications;
}
19
Source : FileHelper.cs
with MIT License
from feiyit
with MIT License
from feiyit
public bool FileMove(string source, string destination)
{
bool ret = false;
FileInfo file_s = new FileInfo(source);
FileInfo file_d = new FileInfo(destination);
if (file_s.Exists)
{
if (!file_d.Exists)
{
file_s.MoveTo(destination);
ret = true;
}
}
if (ret == true)
{
//Response.Write("<script>alert('剪切文件成功!');</script>");
}
else
{
//Response.Write("<script>alert('剪切文件失败!');</script>");
}
return ret;
}
19
Source : FileImporter.cs
with MIT License
from ForkGG
with MIT License
from ForkGG
private void DirectoryMoveInternal(string sourceDirName, string destDirName, bool moveSubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.MoveTo(temppath, true);
eventArgs.FilesCopied++;
OnCopyProgressChanged(eventArgs);
}
// If copying subdirectories, copy them and their contents to new location.
if (moveSubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryMoveInternal(subdir.FullName, temppath, moveSubDirs);
}
}
}
19
Source : PluginManager.cs
with MIT License
from ForkGG
with MIT License
from ForkGG
private bool DisablePlugin(InstalledPlugin plugin, PluginViewModel viewModel)
{
try
{
if (!plugin.IsEnabled)
{
return true;
}
FileInfo jarFile = new FileInfo(Path.Combine(App.ServerPath,
viewModel.EnreplacedyViewModel.Name, "plugins", StringUtils.PluginNameToJarName(plugin.Name) + ".jar"));
if (!jarFile.Exists)
{
ErrorLogger.Append(new ArgumentException(
".jar for plugin " + plugin.Name +
" was not found. Can't disable it. Removing it from the list..."));
Application.Current.Dispatcher?.Invoke(() => viewModel.InstalledPlugins.Remove(plugin));
}
else
{
DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(App.ServerPath,
viewModel.EnreplacedyViewModel.Name, "plugins_disabled"));
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
jarFile.MoveTo(Path.Combine(directoryInfo.FullName, jarFile.Name), true);
}
Console.WriteLine("Disabled Plugin " + plugin.Name);
viewModel.DisablePlugin(plugin);
return true;
}
catch (Exception e)
{
ErrorLogger.Append(e);
Console.WriteLine("Error while disabling Plugin " + plugin.Name);
return false;
}
}
19
Source : PluginManager.cs
with MIT License
from ForkGG
with MIT License
from ForkGG
private bool EnablePlugin(InstalledPlugin plugin, PluginViewModel viewModel)
{
try
{
if (plugin.IsEnabled)
{
return true;
}
FileInfo jarFile = new FileInfo(Path.Combine(App.ServerPath,
viewModel.EnreplacedyViewModel.Name, "plugins_disabled",
StringUtils.PluginNameToJarName(plugin.Name) + ".jar"));
if (!jarFile.Exists)
{
ErrorLogger.Append(new ArgumentException(
".jar for plugin " + plugin.Name +
" was not found. Can't enable it. Removing it from the list..."));
Application.Current.Dispatcher?.Invoke(() => viewModel.InstalledPlugins.Remove(plugin));
}
else
{
DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(App.ServerPath,
viewModel.EnreplacedyViewModel.Name, "plugins"));
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
jarFile.MoveTo(Path.Combine(directoryInfo.FullName, jarFile.Name), true);
}
Console.WriteLine("Enabled Plugin " + plugin.Name);
viewModel.EnablePlugin(plugin);
return true;
}
catch (Exception e)
{
ErrorLogger.Append(e);
Console.WriteLine("Error while enabling Plugin " + plugin.Name);
return false;
}
}
19
Source : MoveFileActivity.cs
with GNU General Public License v3.0
from FreeDemon2020
with GNU General Public License v3.0
from FreeDemon2020
protected override void Execute(CodeActivityContext context)
{
try
{
string filePath = Path.Get(context);
FileInfo file = new FileInfo(filePath);
string desFilePath = Destination.Get(context);
string DestinationPath = desFilePath;
FileInfo desFile = new FileInfo(desFilePath);
if(desFile.Name=="")
{
DestinationPath = desFilePath+ file.Name;
}
if (file.Exists)
{
if(File.Exists(DestinationPath))
{
if(Overwrite)
{
File.Delete(DestinationPath);
}
else
{
SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", "有重复文件!");
return;
}
}
file.MoveTo(DestinationPath);
}
else
{
SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", "文件复制失败");
}
}
catch
{
SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", "文件复制失败");
if (ContinueOnError.Get(context))
{
}
else
{
throw;
}
}
}
19
Source : FileHelper.cs
with MIT License
from geberit
with MIT License
from geberit
public static FileInfo MoveWithLock( string aOriginalFileName, string aDestFileName, int aWait = 100, int aMaxWait = 1000 )
{
if( string.IsNullOrEmpty( aOriginalFileName ) ) throw new ArgumentException( nameof( aOriginalFileName ) );
if( string.IsNullOrEmpty( aDestFileName ) ) throw new ArgumentException( nameof( aDestFileName ) );
if( aWait < 0 ) throw new ArgumentException( nameof( aWait ) );
if( aMaxWait < 0 ) throw new ArgumentException( nameof( aMaxWait ) );
FileInfo result = null;
bool check = false;
try {
check = IoRetry( () => {
FileInfo file = new FileInfo( aOriginalFileName );
if( file.Exists ) file.MoveTo( aDestFileName );
}, aWait, aMaxWait );
}
catch( FileNotFoundException ) {
}
if( check ) result = new FileInfo( aDestFileName );
return result;
}
19
Source : Program.cs
with MIT License
from GEEKiDoS
with MIT License
from GEEKiDoS
static void ProcessFileSystemEntry(FileSystemInfo fileSystemInfo)
{
if (fileSystemInfo is DirectoryInfo directoryInfo)
{
foreach (var fsi in directoryInfo.GetFileSystemInfos())
ProcessFileSystemEntry(fsi);
}
else if (fileSystemInfo is FileInfo fileInfo)
{
if (fileInfo.Name == "MusicMaster.json")
{
musicMaster = JsonConvert.DeserializeAnonymousType(File.ReadAllText(fileInfo.FullName), musicMaster);
}
else if (fileInfo.Name == "UnitMaster.json")
{
unitMaster = JsonConvert.DeserializeAnonymousType(File.ReadAllText(fileInfo.FullName), unitMaster);
}
else if (fileInfo.Extension == ".mp3" && fileInfo.Name.StartsWith("music_"))
{
int mid = int.Parse(fileInfo.Name.Replace("music_", "").Replace(".mp3", ""));
if (!musicMaster.ContainsKey(mid))
return;
var musicInfo = musicMaster[mid];
musicInfo.FindMyUnit(unitMaster);
var file = TagLib.File.Create(fileInfo.FullName);
file.Tag.replacedle = musicInfo.Name;
static string[] SplitArtistNames(string str)
{
// hack for DJ'TEKINA//SOMETHING
str.Replace("//", "👴");
if (str.Contains("、"))
return str.Split('、');
else if (str.Contains("/"))
return str.Split('/');
else return new string[] { str.Replace("👴", "//") };
}
if (musicInfo.__UnitPrimaryKey__ == 30)
{
file.Tag.Performers = new string[] { musicInfo.SpecialUnitName };
}
else if (musicInfo.__UnitPrimaryKey__ == 50)
{
List<string> ps = new();
ps.AddRange(SplitArtistNames(musicInfo.Arranger.Replace("(Elements Garden)", "")));
ps.AddRange(SplitArtistNames(musicInfo.Composer.Replace("(Elements Garden)", "")));
ps.AddRange(SplitArtistNames(musicInfo.Lyrist.Replace("(Elements Garden)", "")));
file.Tag.Performers = ps.Distinct().ToArray();
}
else
{
file.Tag.Performers = new string[] { musicInfo.Unit.Name };
}
file.Tag.Conductor = musicInfo.Arranger;
file.Tag.Composers = SplitArtistNames(musicInfo.Composer);
file.Tag.BeatsPerMinute = (uint)musicInfo.MusicBpm;
file.Tag.Year = (uint)musicInfo.StartDate.Year;
file.Tag.Album = $"D4DJ Groovy Mix - {musicInfo.Category}";
file.Tag.AlbumArtists = new string[] { "Bushiroad" };
file.Save();
var fileName = musicInfo.Name.Replace(':', ':')
.Replace('*', '*')
.Replace('?', '?')
.Replace('"', '"');
fileName += $" - {string.Join(',', file.Tag.Performers)}";
Console.WriteLine($"Renaming {fileInfo.Name} to {fileName}.mp3");
fileInfo.MoveTo($"{fileInfo.FullName.Replace(fileInfo.Name, fileName)}.mp3");
}
}
}
19
Source : CampaignWindow.xaml.cs
with GNU General Public License v3.0
from GlowPuff
with GNU General Public License v3.0
from GlowPuff
private void removeScenario_Click( object sender, RoutedEventArgs e )
{
bool doDelete = false;
if ( System.Windows.Input.Keyboard.IsKeyDown( System.Windows.Input.Key.LeftCtrl ) || System.Windows.Input.Keyboard.IsKeyDown( System.Windows.Input.Key.RightCtrl ) )
doDelete = true;
string basePath = Path.Combine( Environment.GetFolderPath( Environment.SpecialFolder.MyDoreplacedents ), "Your Journey" );
CampaignItem ci = (CampaignItem)( (Button)sender ).DataContext;
if ( doDelete )
{
var res = MessageBox.Show( "Are you sure you want to PERMANENTLY DELETE the Scenario?\r\n\r\n" + ci.scenarioName + "\r\n\r\n" + Path.Combine( campaignFolder, ci.fileName ), "Confirm Scenario Deletion", MessageBoxButton.YesNo, MessageBoxImage.Question );
if ( res == MessageBoxResult.Yes )
{
campaign.scenarioCollection.Remove( ci );
FileInfo fi = new FileInfo( Path.Combine( campaignFolder, ci.fileName ) );
fi.Delete();
SaveCampaign();
}
}
else
{
campaign.scenarioCollection.Remove( ci );
SaveCampaign();
//move scenario file back into main project folder
FileInfo fi = new FileInfo( Path.Combine( campaignFolder, ci.fileName ) );
string moveto = Path.Combine( Path.Combine( basePath, ci.fileName ) );
fi.MoveTo( moveto );
//open the scenario and set its campaign GUID to empty
Scenario scenario = FileManager.LoadProject( ci.fileName );
if ( scenario != null )
{
scenario.campaignGUID = Guid.Empty;
scenario.projectType = ProjectType.Standalone;
FileManager fm = new FileManager( scenario );
fm.Save();
}
else
{
MessageBox.Show( "Could not open the Scenario to reset its Campaign setting to Empty.\r\nTried to modify: " + campaignFolder + ci.fileName, "App Exception", MessageBoxButton.OK, MessageBoxImage.Error );
}
}
}
19
Source : CampaignWindow.xaml.cs
with GNU General Public License v3.0
from GlowPuff
with GNU General Public License v3.0
from GlowPuff
private void addExisting_Click( object sender, RoutedEventArgs e )
{
string basePath = Path.Combine( Environment.GetFolderPath( Environment.SpecialFolder.MyDoreplacedents ), "Your Journey" );
//check regular scenario project path
if ( !Directory.Exists( basePath ) )
{
var di = Directory.CreateDirectory( basePath );
if ( di == null )
{
MessageBox.Show( "Could not create the scenario project folder.\r\nTried to create: " + basePath, "App Exception", MessageBoxButton.OK, MessageBoxImage.Error );
return;
}
}
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = ".jime";
ofd.replacedle = "Add Scenario to Campaign";
ofd.Filter = "Journey File (*.jime)|*.jime";
ofd.InitialDirectory = basePath;
if ( ofd.ShowDialog() == true )
{
var s = FileManager.LoadProject( ofd.SafeFileName );
if ( s != null )
{
CampaignItem ci = new CampaignItem();
ci.scenarioName = s.scenarioName;
ci.fileName = ofd.SafeFileName;
campaign.scenarioCollection.Add( ci );
//save campaign
SaveCampaign();
//move scenario file from project folder to campaign folder
FileInfo fi = new FileInfo( ofd.FileName );
string moveto = Path.Combine( campaignFolder, ofd.SafeFileName );
fi.MoveTo( moveto );
//open the scenario and add the campaign GUID to it, resave
Scenario scenario = FileManager.LoadProjectFromPath( campaignFolder, ci.fileName );
if ( scenario != null )
{
scenario.campaignGUID = campaign.campaignGUID;
scenario.projectType = ProjectType.Campaign;
FileManager fm = new FileManager( scenario );
fm.Save();
}
else
{
MessageBox.Show( "Could not modify the Scenario to use a Campaign.\r\nTried to modify: " + campaignFolder + ci.fileName, "App Exception", MessageBoxButton.OK, MessageBoxImage.Error );
}
}
}
}
19
Source : EditorTools.cs
with MIT License
from gmhevinci
with MIT License
from gmhevinci
public static void FileMoveTo(string filePath, string destPath)
{
FileInfo fileInfo = new FileInfo(filePath);
fileInfo.MoveTo(destPath);
}
19
Source : EditorTools.cs
with MIT License
from gmhevinci
with MIT License
from gmhevinci
public static void FileRename(string filePath, string newName)
{
string dirPath = Path.GetDirectoryName(filePath);
string destPath;
if (Path.HasExtension(filePath))
{
string extentsion = Path.GetExtension(filePath);
destPath = $"{dirPath}/{newName}{extentsion}";
}
else
{
destPath = $"{dirPath}/{newName}";
}
FileInfo fileInfo = new FileInfo(filePath);
fileInfo.MoveTo(destPath);
}
19
Source : TestIFileDataFlowComponents.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
public IList<FileInfo> ProcessPipelineData(IList<FileInfo> toProcess, IDataLoadEventListener listener)
{
if (DestinationDirectory.Parent == null)
throw new Exception("The destination directory has no parent so a new set of filepaths cannot be created.");
var movedFiles = new List<FileInfo>();
foreach (var fileInfo in toProcess.ToList())
{
var filePath = Path.Combine(DestinationDirectory.Parent.FullName, "...?");
fileInfo.MoveTo(filePath);
movedFiles.Add(new FileInfo(filePath));
}
return movedFiles;
}
19
Source : TestDataWriter.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
public TestDataWriterChunk ProcessPipelineData(TestDataWriterChunk toProcess, IDataLoadEventListener listener, GracefulCancellationToken cancellationToken)
{
var layout = CreateCacheLayout();
var toCreateFilesIn = layout.Resolver.GetLoadCacheDirectory(CacheDirectory);
foreach (FileInfo file in toProcess.Files)
{
string destination = Path.Combine(toCreateFilesIn.FullName, file.Name);
if(File.Exists(destination))
File.Delete(destination);
file.MoveTo(destination);
}
return null;
}
19
Source : ExtensionMethods.cs
with GNU General Public License v3.0
from hitchhiker
with GNU General Public License v3.0
from hitchhiker
public static FileInfo RenameExt(this FileInfo source, string ext)
{
if (string.IsNullOrEmpty(ext))
ext = "";
else if (!ext.StartsWith("."))
ext = "." + ext;
var np = Path.ChangeExtension(source.FullName, ext);
if (!source.Exists)
return new FileInfo(np);
var nfi = new FileInfo(np);
if (nfi.FullName.Equals(source.FullName, StringComparison.OrdinalIgnoreCase))
return source;
if (nfi.Exists)
{
nfi.Delete();
}
source.MoveTo(nfi.FullName);
source.Refresh();
return source;
}
19
Source : ExtensionMethods.cs
with GNU General Public License v3.0
from hitchhiker
with GNU General Public License v3.0
from hitchhiker
public static FileInfo Rename(this FileInfo source, string name)
{
if (string.IsNullOrEmpty(name))
return null;
var fp = source.FullName.Substring(0, source.FullName.Length - source.Name.Length);
var np = Path.Combine(fp, name);
if (!source.Exists)
return new FileInfo(np);
var nfi = new FileInfo(np);
if (nfi.FullName.Equals(source.FullName, StringComparison.OrdinalIgnoreCase))
return source;
if (nfi.Exists)
{
nfi.Delete();
}
source.MoveTo(nfi.FullName);
source.Refresh();
return source;
}
19
Source : ImportBeatmapTest.cs
with MIT License
from hornyyy
with MIT License
from hornyyy
[Test]
public async Task TestImportThenImportWithDifferentFilename()
{
using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest)))
{
try
{
var osu = LoadOsuIntoHost(host);
var temp = TestResources.GetTestBeatmapForImport();
string extractedFolder = $"{temp}_extracted";
Directory.CreateDirectory(extractedFolder);
try
{
var imported = await LoadOszIntoOsu(osu);
using (var zip = ZipArchive.Open(temp))
zip.WriteToDirectory(extractedFolder);
// change filename
var firstFile = new FileInfo(Directory.GetFiles(extractedFolder).First());
firstFile.MoveTo(Path.Combine(firstFile.DirectoryName, $"{firstFile.Name}-changed{firstFile.Extension}"));
using (var zip = ZipArchive.Create())
{
zip.AddAllFromDirectory(extractedFolder);
zip.SaveTo(temp, new ZipWriterOptions(CompressionType.Deflate));
}
var importedSecondTime = await osu.Dependencies.Get<BeatmapManager>().Import(new ImportTask(temp));
ensureLoaded(osu);
// check the newly "imported" beatmap is not the original.
replacedert.IsTrue(imported.ID != importedSecondTime.ID);
replacedert.IsTrue(imported.Beatmaps.First().ID != importedSecondTime.Beatmaps.First().ID);
}
finally
{
Directory.Delete(extractedFolder, true);
}
}
finally
{
host.Exit();
}
}
}
See More Examples