Here are the examples of the csharp api System.IO.File.GetLastWriteTimeUtc(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
133 Examples
19
Source : Frontend.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public Stream? OpenContent(string path, out string pathNew, out DateTime? lastMod, out string? contentType) {
pathNew = path;
try {
string dir = Path.GetFullPath(Settings.ContentRoot);
string pathFS = Path.GetFullPath(Path.Combine(dir, path));
if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
lastMod = File.GetLastWriteTimeUtc(pathFS);
contentType = GetContentType(pathFS);
return File.OpenRead(pathFS);
}
} catch {
}
#if DEBUG
try {
string dir = Path.GetFullPath(Path.Combine("..", "..", "..", "Content"));
string pathFS = Path.GetFullPath(Path.Combine(dir, path));
if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
lastMod = File.GetLastWriteTimeUtc(pathFS);
contentType = GetContentType(pathFS);
return File.OpenRead(pathFS);
}
} catch {
}
try {
string dir = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "CelesteNet.Server.FrontendModule", "Content"));
string pathFS = Path.GetFullPath(Path.Combine(dir, path));
if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
lastMod = File.GetLastWriteTimeUtc(pathFS);
contentType = GetContentType(pathFS);
return File.OpenRead(pathFS);
}
} catch {
}
#endif
if (!path.EndsWith("/index.html")) {
path = path.EndsWith("/") ? path : (path + "/");
Stream? index = OpenContent(path + "index.html", out _, out lastMod, out contentType);
if (index != null) {
pathNew = path;
return index;
}
}
lastMod = null;
contentType = GetContentType(path);
return typeof(CelesteNetServer).replacedembly.GetManifestResourceStream("Celeste.Mod.CelesteNet.Server.Content." + path.Replace("/", "."));
}
19
Source : LocalFileLocator.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
public override DateTime GetLastWriteTimeUtc(string path)
{
return File.GetLastWriteTimeUtc(Path.Combine(_dir, path));
}
19
Source : Utils.cs
with MIT License
from Alprog
with MIT License
from Alprog
public static DateTime GetLastWriteTimeInDirectory(string path)
{
var maxTime = DateTime.MinValue;
foreach (var filePath in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories))
{
if (filePath.EndsWith(".meta"))
{
continue;
}
var time = File.GetLastWriteTimeUtc(filePath);
if (time > maxTime)
{
maxTime = time;
}
}
return maxTime;
}
19
Source : FileSystemCache.cs
with MIT License
from Alprog
with MIT License
from Alprog
public static FileCache GetFileCache(string path)
{
if (!File.Exists(path))
{
return null;
}
var time = File.GetLastWriteTimeUtc(path);
if (FileCaches.TryGetValue(path, out var fileCache))
{
if (time == fileCache.LastWriteTime)
{
return fileCache;
}
}
var bytes = File.ReadAllBytes(path);
fileCache = new FileCache(time, bytes);
FileCaches[path] = fileCache;
return fileCache;
}
19
Source : FileSystemCache.cs
with MIT License
from Alprog
with MIT License
from Alprog
public static void WriteAllText(string path, string text)
{
var currentText = ReadAllText(path);
if (currentText == text)
{
return;
}
File.WriteAllText(path, text);
var time = File.GetLastWriteTimeUtc(path);
FileCaches[path] = new FileCache(time, null, text);
}
19
Source : FileSystemCache.cs
with MIT License
from Alprog
with MIT License
from Alprog
public static void WriteAllBytes(string path, byte[] bytes)
{
string text = null;
var currentText = ReadAllText(path);
if (currentText != null)
{
text = Encoding.UTF8.GetString(bytes);
if (currentText == text)
{
return;
}
}
File.WriteAllBytes(path, bytes);
var time = File.GetLastWriteTimeUtc(path);
FileCaches[path] = new FileCache(time, bytes, text);
}
19
Source : OpenVPNSession.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
protected override void DoRun()
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
try
{
try
{
// Start OpenVPN management interface on IPv4 loopack interface (any TCP free port).
var mgmtServer = new TcpListener(IPAddress.Loopback, 0);
mgmtServer.Start();
try
{
try
{
// Purge stale log files.
var timestamp = DateTime.UtcNow.Subtract(new TimeSpan(30, 0, 0, 0));
foreach (var f in Directory.EnumerateFiles(WorkingFolder, "*.txt", SearchOption.TopDirectoryOnly))
{
SessionAndWindowInProgress.Token.ThrowIfCancellationRequested();
if (File.GetLastWriteTimeUtc(f) <= timestamp)
{
try { File.Delete(LogPath); }
catch { }
}
}
}
catch (OperationCanceledException) { throw; }
catch (Exception) { /* Failure to remove stale log files is not fatal. */ }
try
{
// Save OpenVPN configuration file.
using (var fs = new FileStream(
ConfigurationPath,
FileMode.Create,
FileAccess.Write,
FileShare.Read,
1048576,
FileOptions.SequentialScan))
using (var sw = new StreamWriter(fs))
{
// Save profile's configuration to file.
if (Properties.SettingsEx.Default.OpenVPNRemoveOptions is StringCollection openVPNRemoveOptions)
{
// Remove options on the OpenVPNRemoveOptions list on the fly.
using (var sr = new StringReader(ProfileConfig))
{
string inlineTerm = null;
bool inlineRemove = false;
for (; ; )
{
var line = sr.ReadLine();
if (line == null)
break;
var trimmedLine = line.Trim();
if (!string.IsNullOrEmpty(trimmedLine))
{
// Not an empty line.
if (inlineTerm == null)
{
// Not inside an inline option block = Regular parsing mode.
if (!trimmedLine.StartsWith("#") &&
!trimmedLine.StartsWith(";"))
{
// Not a comment.
var option = eduOpenVPN.Configuration.ParseParams(trimmedLine);
if (option.Count > 0)
{
if (option[0].StartsWith("<") && !option[0].StartsWith("</") && option[0].EndsWith(">"))
{
// Start of an inline option.
var o = option[0].Substring(1, option[0].Length - 2);
inlineTerm = "</" + o + ">";
inlineRemove = openVPNRemoveOptions.Contains(o);
if (inlineRemove)
{
sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
line = "# " + line;
}
}
else if (openVPNRemoveOptions.Contains(option[0]))
{
sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
line = "# " + line;
}
}
}
}
else
{
// Inside an inline option block.
if (inlineRemove)
{
// Remove the inline option content.
line = "# " + line;
}
if (trimmedLine == inlineTerm)
{
// Inline option terminator found. Returning to regular parsing mode.
inlineTerm = null;
}
}
}
sw.WriteLine(line);
}
}
}
else
sw.Write(ProfileConfig);
// Append eduVPN Client specific configuration directives.
sw.WriteLine();
sw.WriteLine();
sw.WriteLine("# eduVPN Client for Windows");
// Introduce ourself (to OpenVPN server).
var replacedembly = replacedembly.GetExecutingreplacedembly();
var replacedemblyreplacedleAttribute = Attribute.GetCustomAttributes(replacedembly, typeof(replacedemblyreplacedleAttribute)).SingleOrDefault() as replacedemblyreplacedleAttribute;
var replacedemblyVersion = replacedembly?.GetName()?.Version;
sw.WriteLine("setenv IV_GUI_VER " + eduOpenVPN.Configuration.EscapeParamValue(replacedemblyreplacedleAttribute?.replacedle + " " + replacedemblyVersion?.ToString()));
// Configure log file (relative to WorkingFolder).
sw.WriteLine("log-append " + eduOpenVPN.Configuration.EscapeParamValue(ConnectionId + ".txt"));
// Configure interaction between us and openvpn.exe.
sw.WriteLine("management " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Address.ToString()) + " " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Port.ToString()) + " stdin");
sw.WriteLine("management-client");
sw.WriteLine("management-hold");
sw.WriteLine("management-query-preplacedwords");
sw.WriteLine("management-query-remote");
// Configure client certificate.
sw.WriteLine("cert " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
sw.WriteLine("key " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
// Ask when username/preplacedword is denied.
sw.WriteLine("auth-retry interact");
sw.WriteLine("auth-nocache");
// Set Wintun interface to be used.
sw.Write("windows-driver wintun\n");
sw.Write("dev-node " + eduOpenVPN.Configuration.EscapeParamValue(Properties.Settings.Default.Clientreplacedle) + "\n");
#if DEBUG
// Renegotiate data channel every 5 minutes in debug versions.
sw.WriteLine("reneg-sec 300");
#endif
if (Environment.OSVersion.Version < new Version(6, 2))
{
// Windows 7 is using tiny 8kB send/receive socket buffers by default.
// Increase to 64kB which is default from Windows 8 on.
sw.WriteLine("sndbuf 65536");
sw.WriteLine("rcvbuf 65536");
}
var openVPNAddOptions = Properties.SettingsEx.Default.OpenVPNAddOptions;
if (!string.IsNullOrWhiteSpace(openVPNAddOptions))
{
sw.WriteLine();
sw.WriteLine();
sw.WriteLine("# Added by OpenVPNAddOptions setting:");
sw.WriteLine(openVPNAddOptions);
}
}
}
catch (OperationCanceledException) { throw; }
catch (Exception ex) { throw new AggregateException(string.Format(Resources.Strings.ErrorSavingProfileConfiguration, ConfigurationPath), ex); }
bool retry;
do
{
retry = false;
// Connect to OpenVPN Interactive Service to launch the openvpn.exe.
using (var openvpnInteractiveServiceConnection = new eduOpenVPN.InteractiveService.Session())
{
var mgmtPreplacedword = Membership.GeneratePreplacedword(16, 6);
try
{
openvpnInteractiveServiceConnection.Connect(
string.Format("openvpn{0}\\service", InstanceName),
WorkingFolder,
new string[] { "--config", ConnectionId + ".conf", },
mgmtPreplacedword + "\n",
3000,
SessionAndWindowInProgress.Token);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex) { throw new AggregateException(Resources.Strings.ErrorInteractiveService, ex); }
try
{
// Wait and accept the openvpn.exe on our management interface (--management-client parameter).
var mgmtClientTask = mgmtServer.AcceptTcpClientAsync();
try { mgmtClientTask.Wait(30000, SessionAndWindowInProgress.Token); }
catch (AggregateException ex) { throw ex.InnerException; }
var mgmtClient = mgmtClientTask.Result;
try
{
// Start the management session.
ManagementSession.Start(mgmtClient.GetStream(), mgmtPreplacedword, SessionAndWindowInProgress.Token);
// Initialize session and release openvpn.exe to get started.
ManagementSession.SetVersion(3, SessionAndWindowInProgress.Token);
ManagementSession.ReplayAndEnableState(SessionAndWindowInProgress.Token);
ManagementSession.ReplayAndEnableEcho(SessionAndWindowInProgress.Token);
ManagementSession.SetByteCount(5, SessionAndWindowInProgress.Token);
ManagementSession.ReleaseHold(SessionAndWindowInProgress.Token);
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--));
try
{
// Wait for the session to end gracefully.
ManagementSession.Monitor.Join();
if (ManagementSession.Error != null && !(ManagementSession.Error is OperationCanceledException))
{
// Session reported an error. Retry.
retry = true;
}
}
finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++)); }
}
finally { mgmtClient.Close(); }
}
finally
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
() =>
{
// Cleanup status properties.
State = SessionStatusType.Disconnecting;
StateDescription = Resources.Strings.OpenVPNStateTypeExiting;
TunnelAddress = null;
IPv6TunnelAddress = null;
ConnectedAt = null;
BytesIn = null;
BytesOut = null;
}));
// Wait for openvpn.exe to finish. Maximum 30s.
try { Process.GetProcessById(openvpnInteractiveServiceConnection.ProcessId)?.WaitForExit(30000); }
catch (ArgumentException) { }
}
}
} while (retry);
}
finally
{
mgmtServer.Stop();
}
}
finally
{
// Delete profile configuration file. If possible.
try { File.Delete(ConfigurationPath); }
catch { }
}
}
finally
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
() =>
{
// Cleanup status properties.
State = SessionStatusType.Disconnected;
StateDescription = "";
Wizard.TaskCount--;
}));
PropertyUpdater.Stop();
}
}
19
Source : MediaProviderService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private IReadOnlyCollection<MediaFile> GetMediaFilesInFolder(string? folder)
{
if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
{
return Array.Empty<MediaFile>();
}
var files = Directory.GetFiles(folder);
var result = new List<MediaFile>(files.Length);
foreach (var file in files)
{
var mediaType = GetSupportedMediaType(file);
if (mediaType != null)
{
var lastChanged = File.GetLastWriteTimeUtc(file);
result.Add(new MediaFile
{
FullPath = file,
MediaType = mediaType,
LastChanged = lastChanged.Ticks,
});
}
}
return result;
}
19
Source : TestThumbnails.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
[TestMethod]
public void TestMethod1()
{
ILogLevelSwitchService logSwitchService = new LogLevelSwitchService();
ICommandLineService commandLineService = new CommandLineService();
IDatabaseService db = new DatabaseService();
IOptionsService optionsService = new OptionsService(logSwitchService, commandLineService);
IThumbnailService service = new ThumbnailService(db, optionsService);
service.ClearThumbCache();
var folder = Path.Combine(FileUtils.GetUsersTempFolder(), "OnlyMIntegrationTests");
FileUtils.CreateDirectory(folder);
var filePath = Path.Combine(folder, "TestImage01.jpg");
var bmp = Properties.Resources.Test01;
bmp.Save(filePath, ImageFormat.Jpeg);
var lastWrite = File.GetLastWriteTimeUtc(filePath);
var dummyFfmpegFolder = string.Empty; // not needed when getting image thumbs
var thumb1 = service.GetThumbnail(filePath, dummyFfmpegFolder, MediaClreplacedification.Image, lastWrite.Ticks, out var foundInCache);
replacedert.IsNotNull(thumb1);
replacedert.IsFalse(foundInCache);
// try again to check we get cached version
var thumb2 = service.GetThumbnail(filePath, dummyFfmpegFolder, MediaClreplacedification.Image, lastWrite.Ticks, out foundInCache);
replacedert.IsNotNull(thumb2);
replacedert.IsTrue(foundInCache);
// now send wrong lastchanged value
var thumb3 = service.GetThumbnail(filePath, dummyFfmpegFolder, MediaClreplacedification.Image, 123456, out foundInCache);
replacedert.IsNotNull(thumb3);
replacedert.IsFalse(foundInCache);
service.ClearThumbCache();
}
19
Source : Program.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
public static DateTime? GetModifyTime(string path)
{
if (!File.Exists(path))
{
return null;
}
return File.GetLastWriteTimeUtc(path);
}
19
Source : AppFileProvider.cs
with MIT License
from aspnetrun
with MIT License
from aspnetrun
public virtual DateTime GetLastWriteTimeUtc(string path)
{
return File.GetLastWriteTimeUtc(path);
}
19
Source : AureliaHelper.cs
with MIT License
from aurelia
with MIT License
from aurelia
public static bool IsInAureliaRoot(string targetFileOrFolder, string projectDirectory)
{
var aureliaProjectDirectory = Directory.EnumerateDirectories(projectDirectory, "aurelia_project", SearchOption.AllDirectories).FirstOrDefault();
if (aureliaProjectDirectory == null) { return false; }
var aureliaFile = Path.Combine(aureliaProjectDirectory, AureliaFileName);
if (!File.Exists(aureliaFile)) { return false; }
var lastWriteTime = File.GetLastWriteTimeUtc(aureliaFile);
if (lastWriteTime > LastModifyDate)
{
var jsonFile = File.ReadAllText(aureliaFile);
AureliaCli = JsonConvert.DeserializeObject<AureliaCli>(jsonFile);
LastModifyDate = lastWriteTime;
RootFolder = Path.Combine(Directory.GetParent(aureliaProjectDirectory).FullName, AureliaCli.Paths.Root ?? "").ToLower();
}
if (AureliaCli.Paths == null) { return false; }
if (IsTypescript == null)
{
IsTypescript = AureliaCli.Transpiler.Id.ToLower().Equals("typescript");
}
IsWebpack = string.IsNullOrWhiteSpace(AureliaCli.Bundler?.Id ?? string.Empty) || AureliaCli.Bundler.Id == "webpack";
return targetFileOrFolder.ToLower().Contains(RootFolder);
}
19
Source : KinesisTapProfileRefreshingAWSCredentials.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
protected override CredentialsRefreshState GenerateNewCredentials()
{
if (_warningIntervalSeconds > 0 && File.GetLastWriteTimeUtc(_profileFilePath).AddSeconds(_warningIntervalSeconds) < DateTime.UtcNow)
{
_context?.Logger?.LogWarning($"Credential file {_profileFilePath} maybe have expired. Please check your credential rotator.");
}
return base.GenerateNewCredentials();
}
19
Source : KuduWebUtil.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
internal static void EnsureValidDeploymentXmlSettings(IEnvironment environment)
{
var path = GetSettingsPath(environment);
if (!FileSystemHelpers.FileExists(path)) return;
try
{
var settings = new DeploymentSettingsManager(new XmlSettings.Settings(path));
settings.GetValue(SettingsKeys.TraceLevel);
}
catch (Exception ex)
{
DateTime lastWriteTimeUtc = DateTime.MinValue;
OperationManager.SafeExecute(() => lastWriteTimeUtc = File.GetLastWriteTimeUtc(path));
// trace initialization error
KuduEventSource.Log.KuduException(
ServerConfiguration.GetApplicationName(),
"Startup.cs",
string.Empty,
string.Empty,
string.Format("Invalid '{0}' is detected and deleted. Last updated time was {1}.", path,
lastWriteTimeUtc),
ex.ToString());
File.Delete(path);
}
}
19
Source : KuduWebUtil.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
private static IDeploymentSettingsManager GetDeploymentSettingsManager(IEnvironment environment)
{
var path = GetSettingsPath(environment);
if (!FileSystemHelpers.FileExists(path))
{
return null;
}
IDeploymentSettingsManager result = null;
try
{
var settings = new DeploymentSettingsManager(new XmlSettings.Settings(path));
settings.GetValue(SettingsKeys.TraceLevel);
result = settings;
}
catch (Exception ex)
{
DateTime lastWriteTimeUtc = DateTime.MinValue;
OperationManager.SafeExecute(() => lastWriteTimeUtc = File.GetLastWriteTimeUtc(path));
// trace initialization error
KuduEventSource.Log.KuduException(
ServerConfiguration.GetApplicationName(),
"Startup.cs",
string.Empty,
string.Empty,
string.Format("Invalid '{0}' is detected and deleted. Last updated time was {1}.", path,
lastWriteTimeUtc),
ex.ToString());
File.Delete(path);
}
return result;
}
19
Source : FileIOWithRetriesTests.cs
with MIT License
from AzureAD
with MIT License
from AzureAD
[TestMethod]
public async Task Touch_FiresEvents_Async()
{
_logger.TraceInformation($"Starting test on " + TestHelper.GetOs());
// a directory and a path that do not exist
string dir = Path.Combine(Directory.GetCurrentDirectory(), Guid.NewGuid().ToString());
Directory.CreateDirectory(dir);
string fileName = "testFile";
string path = Path.Combine(dir, fileName);
FileSystemWatcher watcher = new FileSystemWatcher(dir, fileName);
watcher.EnableRaisingEvents = true;
var semapreplaced = new SemapreplacedSlim(0);
int cacheChangedEventFired = 0;
// expect this event to be fired twice
watcher.Changed += (sender, args) =>
{
_logger.TraceInformation("Event fired!");
cacheChangedEventFired++;
semapreplaced.Release();
};
replacedert.IsFalse(File.Exists(path));
try
{
_logger.TraceInformation($"Touch once");
FileIOWithRetries.TouchFile(path, new TraceSourceLogger(_logger));
DateTime initialLastWriteTime = File.GetLastWriteTimeUtc(path);
replacedert.IsTrue(File.Exists(path));
// LastWriteTime is not granular enough
await Task.Delay(50).ConfigureAwait(false);
_logger.TraceInformation($"Touch twice");
FileIOWithRetries.TouchFile(path, new TraceSourceLogger(_logger));
replacedert.IsTrue(File.Exists(path));
DateTime subsequentLastWriteTime = File.GetLastWriteTimeUtc(path);
replacedert.IsTrue(subsequentLastWriteTime > initialLastWriteTime);
_logger.TraceInformation($"Semapreplaced at {semapreplaced.CurrentCount}");
await semapreplaced.WaitAsync(5000).ConfigureAwait(false);
_logger.TraceInformation($"Semapreplaced at {semapreplaced.CurrentCount}");
await semapreplaced.WaitAsync(10000).ConfigureAwait(false);
replacedert.IsTrue(
cacheChangedEventFired==2 ||
cacheChangedEventFired == 3,
"Expecting the event to be fired 2 times as the file is touched 2 times. On Linux, " +
"the file watcher sometimes fires an additional time for the file creation");
}
finally
{
_logger.TraceInformation("Cleaning up");
Trace.WriteLine(_testListener.CurrentLog);
File.Delete(path);
}
}
19
Source : IoTests.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
[Fact]
public async Task IoManagerTestsAsync()
{
var file1 = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName(), $"file1.dat");
var file2 = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName(), $"file2.dat");
Random random = new Random();
List<string> lines = new List<string>();
for (int i = 0; i < 1000; i++)
{
string line = new string(Enumerable.Repeat(Constants.Chars, 100)
.Select(s => s[random.Next(s.Length)]).ToArray());
lines.Add(line);
}
// Single thread file operations.
DigestableSafeMutexIoManager ioman1 = new DigestableSafeMutexIoManager(file1);
// Delete the file if Exist.
ioman1.DeleteMe();
replacedert.False(ioman1.Exists());
replacedert.False(File.Exists(ioman1.DigestFilePath));
// Write the data to the file.
await ioman1.WriteAllLinesAsync(lines);
replacedert.True(ioman1.Exists());
// Check if the digest file is created.
replacedert.True(File.Exists(ioman1.DigestFilePath));
// Read back the content and check.
static bool IsStringArraysEqual(string[] lines1, string[] lines2)
{
if (lines1.Length != lines2.Length)
{
return false;
}
for (int i = 0; i < lines1.Length; i++)
{
string line = lines2[i];
var readLine = lines1[i];
if (!line.Equals(readLine))
{
return false;
}
}
return true;
}
var readLines = await ioman1.ReadAllLinesAsync();
replacedert.True(IsStringArraysEqual(readLines, lines.ToArray()));
// Check digest file, and write only differ logic.
// Write the same content, file should not be written.
var currentDate = File.GetLastWriteTimeUtc(ioman1.FilePath);
await Task.Delay(500);
await ioman1.WriteAllLinesAsync(lines);
var noChangeDate = File.GetLastWriteTimeUtc(ioman1.FilePath);
replacedert.Equal(currentDate, noChangeDate);
// Write different content, file should be written.
currentDate = File.GetLastWriteTimeUtc(ioman1.FilePath);
await Task.Delay(500);
lines.Add("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
await ioman1.WriteAllLinesAsync(lines);
var newContentDate = File.GetLastWriteTimeUtc(ioman1.FilePath);
replacedert.NotEqual(currentDate, newContentDate);
/* The next test is commented out because on mac and on linux File.Open does not lock the file
* it can be still written by the ioman1.WriteAllLinesAsync(). Tried with FileShare.None FileShare.Delete
* FileStream.Lock none of them are working or caused not supported on this platform exception.
* So there is no OP system way to guarantee that the file won't be written during another write operation.
* For example git is using lock files to solve this problem. We are using system wide mutexes.
* For now there is no other way to do this. Some useful links :
* https://stackoverflow.com/questions/2751734/how-do-filesystems-handle-concurrent-read-write
* https://github.com/dotnet/corefx/issues/5964
*/
//using (File.OpenWrite(ioman1.FilePath))
//{
// // Should be OK because the same data is written.
// await ioman1.WriteAllLinesAsync(lines);
//}
//using (File.OpenWrite(ioman1.FilePath))
//{
// // Should fail because different data is written.
// await replacedert.ThrowsAsync<IOException>(async () => await ioman1.WriteAllLinesAsync(lines));
//}
await ioman1.WriteAllLinesAsync(lines);
// Simulate file write error and recovery logic.
// We have only *.new and *.old files.
File.Copy(ioman1.FilePath, ioman1.OldFilePath);
File.Move(ioman1.FilePath, ioman1.NewFilePath);
// At this point there is now OriginalFile.
var newFile = await ioman1.ReadAllLinesAsync();
replacedert.True(IsStringArraysEqual(newFile, lines.ToArray()));
// Add one more line to have different data.
lines.Add("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
await ioman1.WriteAllLinesAsync(lines);
// Check recovery mechanism.
replacedert.True(
File.Exists(ioman1.FilePath) &&
!File.Exists(ioman1.OldFilePath) &&
!File.Exists(ioman1.NewFilePath));
ioman1.DeleteMe();
replacedert.False(ioman1.Exists());
// Check if directory is empty.
var fileCount = Directory.EnumerateFiles(Path.GetDirectoryName(ioman1.FilePath)).Count();
replacedert.Equal(0, fileCount);
// Check Mutex usage on simultaneous file writes.
DigestableSafeMutexIoManager ioman2 = new DigestableSafeMutexIoManager(file2);
await Task.Run(async () =>
{
using (await ioman1.Mutex.LockAsync())
{
// Should not be a problem because they use different Mutexes.
using (await ioman2.Mutex.LockAsync())
{
await ioman1.WriteAllLinesAsync(lines);
await ioman2.WriteAllLinesAsync(lines);
ioman1.DeleteMe();
ioman2.DeleteMe();
}
}
});
// TryReplace test.
var dummyFilePath = $"{ioman1.FilePath}dummy";
var dummyContent = new string[]
{
"banana",
"peach"
};
await File.WriteAllLinesAsync(dummyFilePath, dummyContent);
await ioman1.WriteAllLinesAsync(lines);
ioman1.TryReplaceMeWith(dummyFilePath);
var fruits = await ioman1.ReadAllLinesAsync();
replacedert.True(IsStringArraysEqual(dummyContent, fruits));
replacedert.False(File.Exists(dummyFilePath));
ioman1.DeleteMe();
}
19
Source : EmbeddedFileSet.cs
with GNU Lesser General Public License v3.0
from cnAbp
with GNU Lesser General Public License v3.0
from cnAbp
private DateTimeOffset GetLastModificationTime()
{
var lastModified = DateTimeOffset.UtcNow;
if (!string.IsNullOrEmpty(replacedembly.Location))
{
try
{
lastModified = File.GetLastWriteTimeUtc(replacedembly.Location);
}
catch (PathTooLongException)
{
}
catch (UnauthorizedAccessException)
{
}
}
return lastModified;
}
19
Source : ImageResizerMiddleware.cs
with MIT License
from cocosip
with MIT License
from cocosip
public async Task Invoke(HttpContext context)
{
var path = context.Request.Path;
// hand to next middleware if we are not dealing with an image
if (context.Request.Query.Count == 0 || !IsImagePath(path))
{
await _next.Invoke(context);
return;
}
//图片需要的参数
var resizeParameter = GetResizeParameter(context.Request.Query);
//无参数,不缩放
if (!resizeParameter.HasParams())
{
await _next.Invoke(context);
return;
}
//图片路径
var imagePath = Path.Combine(
_env.WebRootPath,
path.Value.Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar));
//图片不存在
if (!File.Exists(imagePath))
{
await _next.Invoke(context);
return;
}
//图片最后修改时间
var lastWriteTimeUtc = File.GetLastWriteTimeUtc(imagePath);
//图片二进制
byte[] imageBytes = await _imageResizeService.GetImageData(imagePath, resizeParameter, lastWriteTimeUtc);
//无法调整图片,那么就直接返回下一个
if (imageBytes == null || imageBytes.Length <= 0)
{
await _next.Invoke(context);
return;
}
//contentType
context.Response.ContentType = MimeTypeNameUtil.GetMimeName(resizeParameter.Format);
context.Response.ContentLength = imageBytes.Length;
await context.Response.Body.WriteAsync(imageBytes.ToArray(), 0, imageBytes.Length);
}
19
Source : LinkFileMacroFeatureHandler.cs
with MIT License
from codestackdev
with MIT License
from codestackdev
private void UpdateCachedBodyIfNeeded(LinkFileMacroFeatureParameters parameters)
{
LastError = null;
IModelDoc2 refDoc = null;
bool isRefDocLoaded = false;
try
{
if (File.Exists(parameters.LinkedFilePath))
{
LastUpdateStamp = File.GetLastWriteTimeUtc(parameters.LinkedFilePath).Ticks;
refDoc = m_App.GetOpenDoreplacedentByName(parameters.LinkedFilePath) as IModelDoc2;
isRefDocLoaded = refDoc != null;
if (LastUpdateStamp != parameters.FileLastUpdateTimeStamp
|| (isRefDocLoaded && refDoc.GetSaveFlag()) || CachedBodies == null)
{
if (!isRefDocLoaded)
{
m_App.DoreplacedentVisible(false, (int)swDoreplacedentTypes_e.swDocPART);
var docSpec = m_App.GetOpenDocSpec(parameters.LinkedFilePath) as IDoreplacedentSpecification;
docSpec.Silent = true;
docSpec.ReadOnly = true;
refDoc = m_App.OpenDoc7(docSpec);
if (refDoc == null)
{
throw new InvalidOperationException($"Failed to load the referenced file ${docSpec.FileName} with error: {(swFileLoadError_e)docSpec.Error}");
}
}
if (refDoc is IPartDoc)
{
var bodies = (refDoc as IPartDoc).GetBodies2((int)swBodyType_e.swAllBodies, true) as object[];
if (bodies != null && bodies.Any())
{
var resBodies = bodies.Cast<IBody2>().Select(b => b.ICopy()).ToArray();
CachedBodies = resBodies;
}
else
{
throw new InvalidOperationException("No bodies in the referenced doreplacedent");
}
}
else
{
throw new InvalidOperationException("Referenced doreplacedent is not a part");
}
}
}
else
{
throw new FileNotFoundException($"Linked file '${parameters.LinkedFilePath}' is not found");
}
}
catch (Exception ex)
{
LastError = ex;
}
finally
{
m_App.DoreplacedentVisible(true, (int)swDoreplacedentTypes_e.swDocPART);
if (!isRefDocLoaded && refDoc != null)
{
m_App.CloseDoc(refDoc.Getreplacedle());
}
}
}
19
Source : Program.cs
with MIT License
from coldino
with MIT License
from coldino
private bool IsConvertRequired()
{
var clreplacedFile = Path.Combine(Options.TempDir, CLreplacedES_JSON);
if (!File.Exists(clreplacedFile)) return true;
var arkTimestamp = File.GetLastWriteTimeUtc(Options.SaveFile);
var convertTimestamp = File.GetLastWriteTimeUtc(clreplacedFile);
return (arkTimestamp >= convertTimestamp);
}
19
Source : Program.cs
with MIT License
from coldino
with MIT License
from coldino
private bool IsConvertRequired()
{
var clreplacedFile = Path.Combine(Options.TempDir, CLreplacedES_JSON);
if (!File.Exists(clreplacedFile)) return true;
var arkTimestamp = File.GetLastWriteTimeUtc(Options.SaveFile);
var convertTimestamp = File.GetLastWriteTimeUtc(clreplacedFile);
return (arkTimestamp >= convertTimestamp);
}
19
Source : GameContext.cs
with MIT License
from CommitteeOfZero
with MIT License
from CommitteeOfZero
private static bool ValidateBytecodeCache(
string nssFolder,
string bytecodeCacheDir,
string startupScript)
{
static string getModulePath(string rootDir, string fullPath)
{
return Path.ChangeExtension(
Path.GetRelativePath(rootDir, fullPath),
extension: null
);
}
string startupModule = getModulePath(
rootDir: nssFolder,
Path.Combine(nssFolder, startupScript)
);
foreach (string nssFile in Directory
.EnumerateFiles(nssFolder, "*.nss", SearchOption.AllDirectories))
{
string currentModule = getModulePath(rootDir: nssFolder, nssFile);
string nsxPath = Path.ChangeExtension(
Path.Combine(bytecodeCacheDir, currentModule),
"nsx"
);
try
{
using (FileStream nsxStream = File.OpenRead(nsxPath))
{
long nsxTimestamp = NsxModule.GetSourceModificationTime(nsxStream);
long nssTimestamp = new DateTimeOffset(File.GetLastWriteTimeUtc(nssFile))
.ToUnixTimeSeconds();
if (nsxTimestamp != nssTimestamp)
{
return false;
}
}
}
catch
{
if (currentModule.Equals(startupModule, StringComparison.Ordinal))
{
return false;
}
}
}
return true;
}
19
Source : SourceReferenceResolver.cs
with MIT License
from CommitteeOfZero
with MIT License
from CommitteeOfZero
public override long GetModificationTimestamp(ResolvedPath path)
{
return new DateTimeOffset(File.GetLastWriteTimeUtc(path.Value), TimeSpan.Zero)
.ToUnixTimeSeconds();
}
19
Source : FileStorage.cs
with Apache License 2.0
from Dasync
with Apache License 2.0
from Dasync
private static string TryGetETag(string filePath)
{
if (!File.Exists(filePath))
return null;
return new DateTimeOffset(File.GetLastWriteTimeUtc(filePath)).ToString("o");
}
19
Source : FileService.cs
with MIT License
from dukeofharen
with MIT License
from dukeofharen
public DateTime GetModicationDateTime(string path) => File.GetLastWriteTimeUtc(path);
19
Source : AppDataFolder.cs
with Apache License 2.0
from endink
with Apache License 2.0
from endink
public DateTime GetFileLastWriteTimeUtc(string path)
{
return File.GetLastWriteTimeUtc(CombineToPhysicalPath(path));
}
19
Source : XsltContextScript.cs
with BSD 2-Clause "Simplified" License
from fcarver
with BSD 2-Clause "Simplified" License
from fcarver
public XsltContext Get()
{
string file = getFileName();
if (!File.Exists(file)) return null;
if (_alreadyLoaded == null)
{
_alreadyLoadedWasModifiedAt = File.GetLastWriteTimeUtc(file);
_alreadyLoaded = getNewContext();
return _alreadyLoaded;
}
else
{
DateTime lastModifiedAt = File.GetLastWriteTimeUtc(file);
if (lastModifiedAt != _alreadyLoadedWasModifiedAt)
{
_alreadyLoaded = null;
return Get();
}
else
{
return _alreadyLoaded;
}
}
}
19
Source : MSBuildEvaluationFilter.cs
with MIT License
from filipnavara
with MIT License
from filipnavara
protected virtual DateTime GetLastWriteTimeUtcSafely(string file)
{
try
{
return File.GetLastWriteTimeUtc(file);
}
catch
{
return DateTime.UtcNow;
}
}
19
Source : DownloadCache.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
public static void AutoCollect(Log log)
{
if (_hasCollected)
return;
_hasCollected = true;
var timestampFile = Path.Combine(StuffDirectory, ".gc");
if (File.Exists(timestampFile))
{
// Check only once per week to save I/O performance
var timeWrite = File.GetLastWriteTimeUtc(timestampFile);
var timeNow = DateTime.UtcNow;
if ((timeNow - timeWrite).TotalDays < 7.0)
return;
CollectGarbage(log);
}
if (Directory.Exists(StuffDirectory))
File.WriteAllBytes(timestampFile, new byte[0]);
}
19
Source : DownloadCache.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
static void CollectGarbage(Log log, string dir, double days, bool hasLog = false)
{
if (!Directory.Exists(dir))
return;
foreach (var f in Directory.EnumerateFiles(dir))
{
using (new FileLock(log, f))
{
var timeWrite = File.GetLastWriteTimeUtc(f);
var timeNow = DateTime.UtcNow;
if ((timeNow - timeWrite).TotalDays < days)
continue;
if (!hasLog)
{
log.WriteLine("stuff: Collecting garbage", ConsoleColor.Blue);
hasLog = true;
}
Disk.DeleteFile(log, f);
}
}
}
19
Source : CopyPlatformResources.cs
with GNU Lesser General Public License v3.0
from FusedVR
with GNU Lesser General Public License v3.0
from FusedVR
static DateTime GetLastSourceWriteTimeUtc(string sourceDir)
{
var sourceDirectories = Directory.GetDirectories(sourceDir);
var lastWriteTime = Directory.GetLastWriteTimeUtc(sourceDir);
foreach (var directory in sourceDirectories)
{
var lastWriteTimeForDirectory = GetLastSourceWriteTimeUtc(directory);
lastWriteTime = lastWriteTimeForDirectory > lastWriteTime ? lastWriteTimeForDirectory : lastWriteTime;
}
var sourceFiles = Directory.GetFiles(sourceDir);
foreach (var file in sourceFiles)
{
var lastWriteTimeForFile = File.GetLastWriteTimeUtc(file);
lastWriteTime = lastWriteTimeForFile > lastWriteTime ? lastWriteTimeForFile : lastWriteTime;
}
return lastWriteTime;
}
19
Source : FileUtilities.cs
with MIT License
from GGG-KILLER
with MIT License
from GGG-KILLER
internal static DateTime GetFileTimeStamp(string fullPath)
{
RoslynDebug.replacedert(PathUtilities.IsAbsolute(fullPath));
try
{
return File.GetLastWriteTimeUtc(fullPath);
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
19
Source : FileSystem.cs
with Apache License 2.0
from gigya
with Apache License 2.0
from gigya
public Task<DateTime> GetFileLastModified(string filePath)
{
return Task.FromResult(File.GetLastWriteTimeUtc(filePath)); // no async equivalent
}
19
Source : FileWatcher.cs
with MIT License
from gimlichael
with MIT License
from gimlichael
protected override Task HandleSignalingAsync()
{
lock (_locker)
{
var utcLastModified = File.GetLastWriteTimeUtc(Path);
if (ReadFile)
{
using (var stream = new FileStream(Path, FileMode.Open, FileAccess.Read))
{
stream.Position = 0;
var currentChecksum = HashFactory.CreateCrc64().ComputeHash(stream).ToHexadecimalString();
if (Checksum == null) { Checksum = currentChecksum; }
if (!Checksum.Equals(currentChecksum, StringComparison.OrdinalIgnoreCase))
{
SetUtcLastModified(utcLastModified);
OnChangedRaised();
}
Checksum = currentChecksum;
}
}
else if (utcLastModified > UtcCreated)
{
SetUtcLastModified(utcLastModified);
OnChangedRaised();
}
}
return Task.CompletedTask;
}
19
Source : PreScanner.cs
with MIT License
from GridProtectionAlliance
with MIT License
from GridProtectionAlliance
private static bool MetadataOutOfDate(Options options, string fileName, out string message)
{
message = null;
TotalMetadataUpdates++;
if (options.ForceMetadataUpdate)
return true;
FolderMetadata folderMetadata = GetFolderMetadata(options, null, fileName);
if (folderMetadata is null || !folderMetadata.Files.TryGetValue(fileName, out FileMetadata fileMetadata))
return true;
if (File.GetLastWriteTimeUtc(fileName) > fileMetadata.LastUpdate)
return true;
message = $"Metadata for \"{fileName}\" is up to date.{Environment.NewLine}";
TotalMetadataUpdates--;
return false;
}
19
Source : SongBrowserModel.cs
with MIT License
from halsafar
with MIT License
from halsafar
public void UpdateLevelRecords()
{
Stopwatch timer = new Stopwatch();
timer.Start();
// Calculate some information about the custom song dir
String customSongsPath = Path.Combine(Environment.CurrentDirectory, CUSTOM_SONGS_DIR);
String revSlashCustomSongPath = customSongsPath.Replace('\\', '/');
double currentCustomSongDirLastWriteTIme = (File.GetLastWriteTimeUtc(customSongsPath) - EPOCH).TotalMilliseconds;
bool customSongDirChanged = false;
if (_customSongDirLastWriteTime != currentCustomSongDirLastWriteTIme)
{
customSongDirChanged = true;
_customSongDirLastWriteTime = currentCustomSongDirLastWriteTIme;
}
if (!Directory.Exists(customSongsPath))
{
Logger.Error("CustomSong directory is missing...");
return;
}
// Map some data for custom songs
Regex r = new Regex(@"(\d+-\d+)", RegexOptions.IgnoreCase);
Stopwatch lastWriteTimer = new Stopwatch();
lastWriteTimer.Start();
foreach (KeyValuePair<string, CustomPreviewBeatmapLevel> level in SongCore.Loader.CustomLevels)
{
// If we already know this levelID, don't both updating it.
// SongLoader should filter duplicates but in case of failure we don't want to crash
if (!_cachedLastWriteTimes.ContainsKey(level.Value.levelID) || customSongDirChanged)
{
double lastWriteTime = GetSongUserDate(level.Value);
_cachedLastWriteTimes[level.Value.levelID] = lastWriteTime;
}
}
lastWriteTimer.Stop();
Logger.Info("Determining song download time and determining mappings took {0}ms", lastWriteTimer.ElapsedMilliseconds);
// Update song Infos, directory tree, and sort
this.UpdatePlayCounts();
// Signal complete
if (SongCore.Loader.CustomLevels.Count > 0)
{
didFinishProcessingSongs?.Invoke(SongCore.Loader.CustomLevels);
}
timer.Stop();
Logger.Info("Updating songs infos took {0}ms", timer.ElapsedMilliseconds);
}
19
Source : SongBrowserModel.cs
with MIT License
from halsafar
with MIT License
from halsafar
private double GetSongUserDate(CustomPreviewBeatmapLevel level)
{
var coverPath = Path.Combine(level.customLevelPath, level.standardLevelInfoSaveData.coverImageFilename);
DateTime lastTime;
if (File.Exists(coverPath))
{
var lastWriteTime = File.GetLastWriteTimeUtc(coverPath);
var lastCreateTime = File.GetCreationTimeUtc(coverPath);
lastTime = lastWriteTime > lastCreateTime ? lastWriteTime : lastCreateTime;
}
else
{
var lastCreateTime = File.GetCreationTimeUtc(level.customLevelPath);
lastTime = lastCreateTime;
}
return (lastTime - EPOCH).TotalMilliseconds;
}
19
Source : FileSystemStorageService.cs
with MIT License
from havit
with MIT License
from havit
public override DateTime? GetLastModifiedTimeUtc(string fileName)
{
Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(fileName), nameof(fileName));
return File.GetLastWriteTimeUtc(GetFullPath(fileName));
}
19
Source : LocalFileSystemSyncTests.cs
with MIT License
from HighEncryption
with MIT License
from HighEncryption
[TestMethod]
public void SyncModifiedTimestampChange()
{
var testWrapper = TestWrapperFactory
.CreateLocalToLocal(this.TestContext)
.SaveRelationship()
.CreateSimpleSourceStructure();
// First sync job
testWrapper
.CreateSyncJob()
.RunToCompletion()
.VerifySyncSuccess()
.VerifyResultContainsAllFiles()
.VerifyDatabaseHashes();
Logger.Info("Logging database before last modified timestamp change:");
using (var db = testWrapper.Relationship.GetDatabase())
{
TestHelper.LogConfiguration(testWrapper.Relationship.Configuration);
TestHelper.LogDatabase(db);
}
// Update the creation time of a file
string filePath = Path.Combine(testWrapper.SourceAdapter.Config.RootDirectory, "dir1\\file1.txt");
var newModifiedTime = File.GetLastWriteTimeUtc(filePath).AddSeconds(1);
File.SetLastWriteTimeUtc(filePath, newModifiedTime);
// Second sync job
var jobWrapper = testWrapper
.CreateSyncJob();
jobWrapper
.RunToCompletion()
.VerifySyncSuccess()
.VerifyreplacedyzeEntryCount(1)
.VerifyDatabaseHashes();
SyncJob syncJob = (SyncJob)((replacedyzeJob)jobWrapper.CurrentJob).ContinuationJob;
// Verify that only the created timestamp change was detected
var changedSyncEntry = syncJob.replacedyzeResult.AdapterResults[1].EntryResults[0];
replacedert.AreEqual(changedSyncEntry.Flags, SyncEntryChangedFlags.ModifiedTimestamp);
// Verify that the timestamp was copied
filePath = Path.Combine(testWrapper.DestinationAdapter.Config.RootDirectory, "dir1\\file1.txt");
var expectedModifiedTime = File.GetLastWriteTimeUtc(filePath);
replacedert.AreEqual(expectedModifiedTime, newModifiedTime);
}
19
Source : NxlPatcher.cs
with GNU General Public License v3.0
from Hyddwn
with GNU General Public License v3.0
from Hyddwn
private void GetPatchList(bool overrideSettings = false)
{
double entries = FileDownloadInfos.Count;
PatcherContext.UpdateMainProgress(Properties.Resources.CheckingFiles, $"0/{entries}", 0, false, true);
var entry = 0;
foreach (var fileDownloadInfo in FileDownloadInfos)
{
entry++;
PatcherContext.UpdateMainProgress(Properties.Resources.CheckingFiles, $"{entry}/{entries}",
entry / entries * 100, false,
true);
var filePath = fileDownloadInfo.FileName;
if (!overrideSettings)
{
if (filePath.StartsWith("package\\")
&& PatchSettingsManager.Instance.PatcherSettings.IgnorePackageFolder
&& !GetIsNewPackFile(filePath))
continue;
}
if (PatchIgnore.IgnoredFiles.Contains(filePath))
{
Log.Info($"File: '{filePath}' in ignore list, file will not be patched!");
continue;
}
if (fileDownloadInfo.FileInfoType == FileInfoType.Directory)
{
if (Directory.Exists(fileDownloadInfo.FileName)) continue;
Patches.Add(new Patch(fileDownloadInfo, PatchReason.DoesNotExist));
continue;
}
var modified = false;
var fileExists = true;
var actualModified = new DateTime();
var correctSize = true;
long length = 0;
if (File.Exists(filePath))
{
length = new FileInfo(filePath).Length;
actualModified = File.GetLastWriteTimeUtc(filePath);
if (actualModified != fileDownloadInfo.LastModifiedDateTime)
modified = true;
else if (length != fileDownloadInfo.FileSize)
correctSize = false;
}
else
fileExists = false;
if (!correctSize)
{
var patch = new Patch(fileDownloadInfo, PatchReason.SizeNotMatch);
Patches.Add(patch);
Log.Info(Properties.Resources.PatchRequiredForSize, filePath,
patch.PatchReason.LocalizedPatchReason(), fileDownloadInfo.FileSize, length);
continue;
}
if (!fileExists)
{
var patch = new Patch(fileDownloadInfo, PatchReason.DoesNotExist);
Patches.Add(patch);
Log.Info(Properties.Resources.PatchRequiredFor, filePath, patch.PatchReason.LocalizedPatchReason());
continue;
}
if (!modified) continue;
if (actualModified > fileDownloadInfo.LastModifiedDateTime)
{
var patch = new Patch(fileDownloadInfo, PatchReason.Modified);
Patches.Add(patch);
Log.Info(Properties.Resources.PatchRequiredFor, filePath, patch.PatchReason.LocalizedPatchReason());
}
else
{
var patch = new Patch(fileDownloadInfo);
Patches.Add(patch);
Log.Info(Properties.Resources.PatchRequiredFor, filePath, patch.PatchReason.LocalizedPatchReason());
}
}
}
19
Source : Files.cs
with Apache License 2.0
from ILMTitan
with Apache License 2.0
from ILMTitan
internal static Instant GetLastModifiedTime(SystemPath systemPath)
{
return Instant.FromDateTimeUtc(File.GetLastWriteTimeUtc(systemPath.ToString()));
}
19
Source : BlobProvider.cs
with GNU Affero General Public License v3.0
from imazen
with GNU Affero General Public License v3.0
from imazen
private BlobProviderResult? GetFileResult(string virtualPath)
{
var mapping = pathMappings.FirstOrDefault(
m => virtualPath.StartsWith(m.VirtualPath,
m.IgnorePrefixCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal));
if (mapping.PhysicalPath == null || mapping.VirtualPath == null) return null;
var relativePath = virtualPath
.Substring(mapping.VirtualPath.Length)
.Replace('/', Path.DirectorySeparatorChar)
.TrimStart(Path.DirectorySeparatorChar);
var physicalDir = Path.GetFullPath(mapping.PhysicalPath.TrimEnd(Path.DirectorySeparatorChar));
var physicalPath = Path.GetFullPath(Path.Combine(
physicalDir,
relativePath));
if (!physicalPath.StartsWith(physicalDir, StringComparison.Ordinal))
{
return null; //We stopped a directory traversal attack (most likely)
}
var lastWriteTimeUtc = File.GetLastWriteTimeUtc(physicalPath);
if (lastWriteTimeUtc.Year == 1601) // file doesn't exist, preplaced to next middleware
{
return null;
}
return new BlobProviderResult()
{
IsFile = true,
GetBlob = () => Task.FromResult(new BlobProviderFile()
{
Path = physicalPath,
Exists = true,
LastModifiedDateUtc = lastWriteTimeUtc
} as IBlobData)
};
}
19
Source : LicensingSupport.cs
with GNU Affero General Public License v3.0
from imazen
with GNU Affero General Public License v3.0
from imazen
public DateTimeOffset? GetreplacedemblyWriteDate()
{
var path = GetType().replacedembly.Location;
try {
return path != null && File.Exists(path)
? new DateTimeOffset?(File.GetLastWriteTimeUtc(path))
: null;
} catch {
return null;
}
}
19
Source : MultiFolderStorage.cs
with GNU Affero General Public License v3.0
from imazen
with GNU Affero General Public License v3.0
from imazen
public DateTime? TryGetLastWriteTimeUtc(string filename)
{
bool readFailed = false; //To tell non-existent files apart from I/O errors
try
{
filesystem.EnterReadLock();
foreach (var dest in candidateFolders.Except(badReadLocations))
{
var path = Path.Combine(dest, filename);
if (!badReadLocations.Contains(path) && File.Exists(path))
{
try
{
return File.GetLastWriteTimeUtc(path);
}
catch (Exception e)
{
readFailed = true;
AddBadReadLocation(path, new Issue(this.issueSource, "Failed to read write time of " + dataKind + " from location " + path, e.ToString(), IssueSeverity.Warning));
}
}
}
}
finally
{
filesystem.ExitReadLock();
}
if (readFailed)
{
sink.AcceptIssue(new Issue(this.issueSource, "Unable to read write time of " + dataKind + " from disk despite its existence.", null, IssueSeverity.Error));
}
return null;
}
19
Source : Pack.cs
with MIT License
from Inedo
with MIT License
from Inedo
public override async Task<int> RunAsync(CancellationToken cancellationToken)
{
if (this.NoAudit && !string.IsNullOrEmpty(this.Note))
{
Console.Error.WriteLine("--no-audit cannot be used with --note.");
return 2;
}
UniversalPackageMetadata info;
if (string.IsNullOrWhiteSpace(this.Manifest))
{
info = new UniversalPackageMetadata
{
Group = this.Group,
Name = this.Name,
Version = UniversalPackageVersion.TryParse(this.Version),
replacedle = this.replacedle,
Description = this.PackageDescription,
Icon = this.IconUrl
};
}
else
{
if (!File.Exists(this.Manifest))
{
Console.Error.WriteLine($"The manifest file '{this.Manifest}' does not exist.");
return 2;
}
using (var metadataStream = File.OpenRead(this.Manifest))
{
info = await ReadManifestAsync(metadataStream);
}
}
var error = ValidateManifest(info);
if (error != null)
{
Console.Error.WriteLine("Invalid {0}: {1}", string.IsNullOrWhiteSpace(this.Manifest) ? "parameters" : "upack.json", error);
return 2;
}
PrintManifest(info);
if (!this.NoAudit)
{
info["createdDate"] = DateTime.UtcNow.ToString("u");
if (!string.IsNullOrEmpty(this.Note))
{
info["createdReason"] = this.Note;
}
info["createdUsing"] = "upack/" + typeof(Pack).replacedembly.GetName().Version.ToString(3);
info["createdBy"] = Environment.UserName;
}
if (!Directory.Exists(this.SourcePath) && !File.Exists(this.SourcePath))
{
Console.Error.WriteLine($"The source directory '{this.SourcePath}' does not exist.");
return 2;
}
string relativePackageFileName = $"{info.Name}-{info.Version.Major}.{info.Version.Minor}.{info.Version.Patch}.upack";
string targetFileName = Path.Combine(this.TargetDirectory ?? Environment.CurrentDirectory, relativePackageFileName);
if (File.Exists(Path.Combine(this.SourcePath, relativePackageFileName)))
{
Console.Error.WriteLine("Warning: output file already exists in source directory and may be included inadvertently in the package contents.");
}
string tmpPath = Path.GetTempFileName();
using (var builder = new UniversalPackageBuilder(tmpPath, info))
{
if (Directory.Exists(this.SourcePath))
{
await builder.AddContentsAsync(
this.SourcePath,
"/",
true,
s => string.IsNullOrWhiteSpace(this.Manifest) || !string.Equals(s, "upack.json", StringComparison.OrdinalIgnoreCase),
cancellationToken
);
}
else
{
using (var file = File.Open(this.SourcePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
await builder.AddFileAsync(file, Path.GetFileName(this.SourcePath), File.GetLastWriteTimeUtc(this.SourcePath), cancellationToken);
}
}
}
Directory.CreateDirectory(Path.GetDirectoryName(targetFileName));
File.Delete(targetFileName);
File.Move(tmpPath, targetFileName);
return 0;
}
19
Source : GameDataSnapshotViewModel.cs
with MIT License
from Jamiras
with MIT License
from Jamiras
private void LoadFromDisk()
{
int gameCount = 0;
int staticRichPresenceCount = 0;
int leaderboardCount = 0;
int achievementCount = 0;
var oldestFile = DateTime.MaxValue;
var authors = new HashSet<string>();
var systems = new HashSet<int>();
_gamesWithAchievements.Clear();
_gamesWithLeaderboards.Clear();
_gamesWithRichPresence.Clear();
var directory = _settings.DumpDirectory;
var files = Directory.GetFiles(directory, "*.json");
_progress.Reset(files.Length);
_progress.Label = "Processing cached files";
_progress.IsEnabled = true;
foreach (var file in files)
{
if (!_progress.IsEnabled)
break;
_progress.Current++;
var contents = File.ReadAllText(file);
var json = new Jamiras.IO.Serialization.JsonObject(contents);
var patchData = json.GetField("PatchData");
if (patchData.Type != Jamiras.IO.Serialization.JsonFieldType.Object)
{
File.Delete(file);
continue;
}
int gameId = patchData.ObjectValue.GetField("ID").IntegerValue.GetValueOrDefault();
if (gameId == 0)
{
File.Delete(file);
continue;
}
var lastUpdated = File.GetLastWriteTimeUtc(file);
if (lastUpdated < oldestFile)
oldestFile = lastUpdated;
gameCount++;
var richPresence = patchData.ObjectValue.GetField("RichPresencePatch").StringValue;
if (richPresence != null)
{
int index = richPresence.IndexOf("Display:");
if (index != -1)
{
_gamesWithRichPresence.Add(gameId);
bool dynamic = false;
foreach (var line in richPresence.Substring(index).Split('\n'))
{
if (line.Trim().Length == 0)
break;
if (line.Contains("@"))
{
dynamic = true;
break;
}
}
if (!dynamic)
staticRichPresenceCount++;
}
}
var leaderboards = patchData.ObjectValue.GetField("Leaderboards").ObjectArrayValue;
if (leaderboards != null && leaderboards.Any())
{
_gamesWithLeaderboards.Add(gameId);
leaderboardCount += leaderboards.Count();
}
var achievements = patchData.ObjectValue.GetField("Achievements").ObjectArrayValue;
if (achievements != null && achievements.Any())
{
_gamesWithAchievements.Add(gameId);
achievementCount += achievements.Count();
foreach (var achievement in achievements)
authors.Add(achievement.GetField("Author").StringValue);
}
systems.Add(patchData.ObjectValue.GetField("ConsoleID").IntegerValue.GetValueOrDefault());
}
SetValue(GameCountProperty, gameCount);
SetValue(AchievementCountProperty, achievementCount);
SetValue(AchievementGameCountProperty, _gamesWithAchievements.Count);
SetValue(LeaderboardCountProperty, leaderboardCount);
SetValue(LeaderboardGameCountProperty, _gamesWithLeaderboards.Count);
SetValue(RichPresenceCountProperty, _gamesWithRichPresence.Count);
SetValue(StaticRichPresenceCountProperty, staticRichPresenceCount);
SetValue(AuthorCountProperty, authors.Count);
SetValue(SystemCountProperty, systems.Count);
SetValue(LastUpdatedTextProperty, (oldestFile != DateTime.MaxValue) ? oldestFile.ToLocalTime().ToString() : LastUpdatedTextProperty.DefaultValue);
_progress.IsEnabled = false;
_progress.Label = String.Empty;
if (DataRefreshed != null)
DataRefreshed(this, EventArgs.Empty);
}
19
Source : LocalFileSystem.cs
with zlib License
from jasongdove
with zlib License
from jasongdove
public DateTime GetLastWriteTime(string path) =>
Try(File.GetLastWriteTimeUtc(path)).IfFail(() => SystemTime.MinValueUtc);
19
Source : LocalMetadataProvider.cs
with zlib License
from jasongdove
with zlib License
from jasongdove
private async Task<Option<MusicVideoMetadata>> LoadMusicVideoMetadata(string nfoFileName)
{
try
{
await using FileStream fileStream = File.Open(nfoFileName, FileMode.Open, FileAccess.Read);
Option<MusicVideoNfo> maybeNfo = MusicVideoSerializer.Deserialize(fileStream) as MusicVideoNfo;
return maybeNfo.Match<Option<MusicVideoMetadata>>(
nfo => new MusicVideoMetadata
{
MetadataKind = MetadataKind.Sidecar,
DateAdded = DateTime.UtcNow,
DateUpdated = File.GetLastWriteTimeUtc(nfoFileName),
Album = nfo.Album,
replacedle = nfo.replacedle,
Plot = nfo.Plot,
Year = GetYear(nfo.Year, nfo.Premiered),
ReleaseDate = GetAired(nfo.Year, nfo.Premiered),
Genres = nfo.Genres.Map(g => new Genre { Name = g }).ToList(),
Tags = nfo.Tags.Map(t => new Tag { Name = t }).ToList(),
Studios = nfo.Studios.Map(s => new Studio { Name = s }).ToList()
},
None);
}
catch (Exception ex)
{
_logger.LogInformation(ex, "Failed to read music video nfo metadata from {Path}", nfoFileName);
return None;
}
}
19
Source : LocalMetadataProvider.cs
with zlib License
from jasongdove
with zlib License
from jasongdove
private async Task<Option<ShowMetadata>> LoadTelevisionShowMetadata(string nfoFileName)
{
try
{
await using FileStream fileStream = File.Open(nfoFileName, FileMode.Open, FileAccess.Read);
Option<TvShowNfo> maybeNfo = TvShowSerializer.Deserialize(fileStream) as TvShowNfo;
return maybeNfo.Match<Option<ShowMetadata>>(
nfo =>
{
DateTime dateAdded = DateTime.UtcNow;
DateTime dateUpdated = File.GetLastWriteTimeUtc(nfoFileName);
return new ShowMetadata
{
MetadataKind = MetadataKind.Sidecar,
DateAdded = dateAdded,
DateUpdated = dateUpdated,
replacedle = nfo.replacedle,
Plot = nfo.Plot,
Outline = nfo.Outline,
Tagline = nfo.Tagline,
ContentRating = nfo.ContentRating,
Year = GetYear(nfo.Year, nfo.Premiered),
ReleaseDate = GetAired(nfo.Year, nfo.Premiered),
Genres = nfo.Genres.Map(g => new Genre { Name = g }).ToList(),
Tags = nfo.Tags.Map(t => new Tag { Name = t }).ToList(),
Studios = nfo.Studios.Map(s => new Studio { Name = s }).ToList(),
Actors = Actors(nfo.Actors, dateAdded, dateUpdated),
Guids = nfo.UniqueIds
.Map(id => new MetadataGuid { Guid = $"{id.Type}://{id.Guid}" })
.ToList()
};
},
None);
}
catch (Exception ex)
{
_logger.LogInformation(ex, "Failed to read TV show nfo metadata from {Path}", nfoFileName);
return None;
}
}
See More Examples