本文整理汇总了C#中System.IO.FileInfo.Refresh方法的典型用法代码示例。如果您正苦于以下问题:C# FileInfo.Refresh方法的具体用法?C# FileInfo.Refresh怎么用?C# FileInfo.Refresh使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.FileInfo
的用法示例。
在下文中一共展示了FileInfo.Refresh方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Serialize
public static void Serialize(FileInfo file, Action<GenericWriter> serializer)
{
file.Refresh();
if (file.Directory != null && !file.Directory.Exists)
{
file.Directory.Create();
}
if (!file.Exists)
{
file.Create().Close();
}
file.Refresh();
using (var fs = file.OpenWrite())
{
var writer = new BinaryFileWriter(fs, true);
try
{
serializer(writer);
}
finally
{
writer.Flush();
writer.Close();
}
}
}
示例2: Synchronize
public void Synchronize()
{
DirectoryInfo src = new DirectoryInfo("./filehelpersrc");
DirectoryInfo dest = new DirectoryInfo("./filehelperdest");
FileHelper.Synchronize(src, dest, true);
Assert.IsTrue(File.Exists(Path.Combine(dest.FullName, "b")));
string path = Path.Combine(dest.FullName, Path.Combine("subdir", "c"));
Assert.IsTrue(File.Exists(path));
//change
Thread.Sleep(2*2000);
StreamWriter os = File.CreateText(Path.Combine(src.FullName, "c"));
os.WriteLine(1);
os.WriteLine(2);
os.WriteLine(3);
os.Flush();
os.Close();
FileInfo test = new FileInfo(Path.Combine(src.FullName, "c"));
FileInfo destTest = new FileInfo(Path.Combine(dest.FullName, "c"));
Assert.AreNotSame(test.LastWriteTime, destTest.LastWriteTime);
FileHelper.Synchronize(src, dest, true);
destTest.Refresh();
Assert.AreEqual(test.LastWriteTime, destTest.LastWriteTime);
Assert.AreEqual(test.Length, destTest.Length);
//delete file
test.Delete();
FileHelper.Synchronize(src, dest, true);
destTest.Refresh();
Assert.IsTrue(! destTest.Exists);
}
示例3: AddCRC
/// <summary>
/// Add CRC checksum to given filename.
/// </summary>
/// <param name="filename">The fullpath filename.</param>
/// <param name="crc">The CRC code.</param>
/// <param name="newfilename">Just the filename.</param>
/// <returns>The fullpath filename.</returns>
public static string AddCRC(string filename, string crc, out string newfilename)
{
FileInfo file = new FileInfo(filename);
file.Refresh();
file.MoveTo(file.FullName.Insert(file.FullName.Length - (file.Extension.Length), "_[" + crc + "]"));
file.Refresh();
newfilename = Path.GetFileName(file.Name);
return file.FullName;
}
示例4: BundleTest
public void BundleTest()
{
// create bundle
var bundle = CreateBundle();
var bundleFile = new FileInfo(Path.Combine(_temporaryDirectory, Guid.NewGuid().ToString() + ".css.bundle"));
var bundleOutputFile = new System.IO.FileInfo(bundleFile.FullName.Replace(".css.bundle", ".min.css"));
Bundle.Serialize(bundle, bundleFile.FullName);
// move the creation and last write back in time to simulate real world
bundleFile.CreationTimeUtc = DateTime.UtcNow.AddHours(-1);
bundleFile.LastWriteTimeUtc = bundleFile.CreationTimeUtc;
Assert.False(bundleOutputFile.Exists);
// bundle
var bundler = new NUnitBundler();
bundler.Bundle(bundleFile.FullName);
// test to ensure the output file was created
bundleOutputFile.Refresh();
Assert.True(bundleOutputFile.Exists);
var bundleOutputFileLastWriteUtc = bundleOutputFile.LastWriteTimeUtc;
// create a new bundler and do it again
bundler = new NUnitBundler();
bundler.Bundle(bundleFile.FullName);
// test to ensure the output file was created
bundleOutputFile.Refresh();
Assert.True(bundleOutputFile.Exists);
// ensure it hasn't changed since nothing has changed
Assert.AreEqual(bundleOutputFileLastWriteUtc, bundleOutputFile.LastWriteTimeUtc, "The file should not have changed.");
// change the bundle file and do it again
bundle.Includes.RemoveAt(0);
Bundle.Serialize(bundle, bundleFile.FullName);
// create a new bundler and do it again
bundler = new NUnitBundler();
bundler.Bundle(bundleFile.FullName);
// test to ensure the output file was created
bundleOutputFile.Refresh();
Assert.True(bundleOutputFile.Exists);
// ensure the output file HAS changed since we modified the bundle
Assert.Greater(bundleOutputFile.LastWriteTimeUtc, bundleOutputFileLastWriteUtc, "The file should have changed.");
}
示例5: Create
/// <summary>
/// Creates a file from a list of strings; each string is placed on a line in the file.
/// </summary>
/// <param name="TempFileName">Name of response file</param>
/// <param name="Lines">List of lines to write to the response file</param>
public static FileReference Create(FileReference TempFileName, List<string> Lines, CreateOptions Options = CreateOptions.None)
{
FileInfo TempFileInfo = new FileInfo(TempFileName.FullName);
if (TempFileInfo.Exists)
{
if ((Options & CreateOptions.WriteEvenIfUnchanged) != CreateOptions.WriteEvenIfUnchanged)
{
string Body = string.Join(Environment.NewLine, Lines);
// Reuse the existing response file if it remains unchanged
string OriginalBody = File.ReadAllText(TempFileName.FullName);
if (string.Equals(OriginalBody, Body, StringComparison.Ordinal))
{
return TempFileName;
}
}
// Delete the existing file if it exists and requires modification
TempFileInfo.IsReadOnly = false;
TempFileInfo.Delete();
TempFileInfo.Refresh();
}
FileItem.CreateIntermediateTextFile(TempFileName, string.Join(Environment.NewLine, Lines));
return TempFileName;
}
示例6: TakeScreenshot
/// <summary>
/// Method to take screenshot from primary screen, change it's creation time and save it into the folder
/// </summary>
/// <param name="creationTime"></param>
/// <param name="screenPath"></param>
/// <returns></returns>
public static string TakeScreenshot(DateTime creationTime = default(DateTime), string screenPath = "")
{
var format = ImageFormat.Png;
var now = DateTime.Now;
creationTime = creationTime.Equals(default(DateTime)) ? now : creationTime;
var screenName = GetScreenName(creationTime, format);
using (var bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
{
using (var g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
var file = (screenPath.Equals("") ? GetPath() : screenPath) + screenName;
bmpScreenCapture.Save(file, format);
var fileInfo = new FileInfo(file);
fileInfo.Refresh();
fileInfo.CreationTime = creationTime;
}
}
return screenName;
}
示例7: GetArtifactFile
/// <summary>
/// Returns a downloaded artifact.
/// </summary>
/// <param name="artifactURI">The URI to the artifact (may contain a job number or a reference to latest)</param>
/// <returns>A local reference to the artifact downloaded. It should not be modified!</returns>
/// <remarks>
/// If a reference is made to the "latestSuceessful" then the build server will be queried to find the latest successful
/// job number. If the job number is for a file already downloaded, no download will occur. If the uri contains an explicit
/// job number, and that file is already local for that job number, no web access will be made.
///
/// Files are stored in the user's temp directory. Deleting them at anytime is fine (as long as they aren't in direct use!!),
/// as they will be automatically downloaded the next time a query is made.
/// </remarks>
static public async Task<FileInfo> GetArtifactFile(Uri artifactURI)
{
// Fetch access to the server
var jenksInfo = new JenkinsServer(artifactURI);
// Next, determine the job information for this guy
var artifactInfo = await jenksInfo.GetArtifactInfo();
// Build the file path where we will store it. If it is already there,
// then we are done!
var location = new FileInfo($"{Path.GetTempPath()}\\JenkinsArtifactCache\\{artifactInfo.JobName}\\{artifactInfo.BuildNumber}-{artifactInfo.ArtifactName}");
if (location.Exists)
{
return location;
}
// If isn't there, then download it.
await jenksInfo.Download(artifactInfo, location);
location.Refresh();
if (!location.Exists)
{
throw new InvalidOperationException($"Unable to download the Jenkins build artifact at the URL {artifactURI.OriginalString}.");
}
return location;
}
示例8: CheckInfoIsValid
/// <summary>
/// Checks if the NFO file for an episode is a valid NFO file
/// and removes it if not
/// </summary>
/// <param name="episodeFileInfo">FileInfo object</param>
/// <param name="season">Number of the season</param>
/// <param name="episode">Number of the episode</param>
public static void CheckInfoIsValid(ref FileInfo episodeFileInfo, int season, int episode)
{
if (episodeFileInfo.Exists)
{
try
{
FileStream episodeFileInfoStream;
using (episodeFileInfoStream = episodeFileInfo.OpenRead())
{
XDocument xd = XDocument.Load(episodeFileInfoStream);
if (xd.Element("episodedetails") == null)
{
throw new Exception(
string.Format(
"NFO file found, but doesn't contain 'episodedetails' node at '{0}'",
episodeFileInfo));
}
}
}
catch (Exception)
{
// delete the .nfo file
ConsoleLogger.Log("Episode info is invalid: Season '" + season +
"', Episode '" + episode + "'. Deleting.");
if (!CustomConfiguration.DisableAllFileSystemActions)
{
episodeFileInfo.Delete();
}
episodeFileInfo.Refresh();
}
}
}
示例9: Setup
public void Setup()
{
_file = new FileInfo(Path.Combine(@".\Resources", FileName));
_file.Refresh();
Assert.IsTrue(_file.Exists);
_originalImage = Resources.silver_laptop_icon;
}
示例10: TryStripMetadata
public void TryStripMetadata(FileInfo mediaFile)
{
String originalFile = mediaFile.FullName;
String tmpFile = originalFile + ".tmp";
try
{
File.Move(originalFile, tmpFile);
try
{
String ffmpegParameters = String.Format("-i \"{0}\" -map_metadata -1 -vcodec copy -acodec copy \"{1}\"",
tmpFile,
originalFile
);
this.ExecuteProcess(ffmpegParameters);
}
catch (Exception)
{
if (File.Exists(originalFile))
{
File.Delete(originalFile);
}
File.Move(tmpFile, originalFile);
throw;
}
}
finally //The tempfile should always be removed so we dont leave stuff behind.
{
if (File.Exists(tmpFile))
{
File.Delete(tmpFile);
}
}
mediaFile.Refresh();
}
示例11: FileTelemetryConsumer
public FileTelemetryConsumer(FileInfo file)
{
_logFileName = file.FullName;
var fileExists = File.Exists(_logFileName);
_logOutput = fileExists ? file.AppendText() : file.CreateText();
file.Refresh();
}
示例12: SerializableDictionaryTest_Invalid_Encoding
public void SerializableDictionaryTest_Invalid_Encoding()
{
//arrange
var target = new Dictionary<string, string>()
{
{ "Name", "☃ ☁ ☠" },
{ "Email", "☢ ☥ ☺" }
};
DictionaryExtensions.DefaultFileEncoding = Encoding.ASCII;
//act
var file = new FileInfo(Path.Combine(Environment.CurrentDirectory, "SerializedDictionary.txt"));
target.SaveToDisk(file);
//assert
file.Refresh();
Assert.IsTrue(file.Exists);
var result = new Dictionary<string, string>();
result.ReadFromDisk(file);
//reset it
DictionaryExtensions.DefaultFileEncoding = Encoding.UTF8;
//with the wrong encoding this will fail!
Assert.AreNotEqual(target["Name"], result["Name"]);
Assert.AreNotEqual(target["Email"], result["Email"]);
}
示例13: Create
/// <summary>
/// Creates a file from a list of strings; each string is placed on a line in the file.
/// </summary>
/// <param name="TempFileName">Name of response file</param>
/// <param name="Lines">List of lines to write to the response file</param>
public static string Create(string TempFileName, List<string> Lines)
{
FileInfo TempFileInfo = new FileInfo( TempFileName );
DirectoryInfo TempFolderInfo = new DirectoryInfo( TempFileInfo.DirectoryName );
// Delete the existing file if it exists
if( TempFileInfo.Exists )
{
TempFileInfo.IsReadOnly = false;
TempFileInfo.Delete();
TempFileInfo.Refresh();
}
// Create the folder if it doesn't exist
if( !TempFolderInfo.Exists )
{
// Create the
TempFolderInfo.Create();
TempFolderInfo.Refresh();
}
using( FileStream Writer = TempFileInfo.OpenWrite() )
{
using( StreamWriter TextWriter = new StreamWriter( Writer ) )
{
Lines.ForEach( x => TextWriter.WriteLine( x ) );
}
}
return TempFileName;
}
示例14: ReadAssembly
/// <summary>
/// Reads the assembly from the given path, or else loads it from cache.
/// </summary>
/// <param name="path">The patch to read the assembly from.</param>
/// <param name="readSymbols">Whether or not to read symbols.</param>
/// <returns></returns>
public AssemblyDefinition ReadAssembly(string path, bool readSymbols = false)
{
var fileInfo = new FileInfo(path);
fileInfo.Refresh();
if (_cache.ContainsKey(path)) {
if (DoesCacheMatch(fileInfo, _cache[path].Metadata)) {
return _cache[path].Assembly;
}
}
var defAssemblyResolver = new ExpandedAssemblyResolver();
defAssemblyResolver.AddSearchDirectory(Path.GetDirectoryName(path));
var rdrParams = new ReaderParameters() {
AssemblyResolver = defAssemblyResolver,
ReadSymbols = readSymbols
};
var read = AssemblyDefinition.ReadAssembly(path, rdrParams);
var assemblyResolver = read.MainModule.AssemblyResolver as BaseAssemblyResolver;
//Cecil doesn't add the assembly's original directory as a search path by default.
var dir = Path.GetDirectoryName(path);
var entry = new AssemblyCacheEntry() {
Assembly = read,
Metadata = new FileMetadata() {
Length = fileInfo.Length,
LastWriteTime = fileInfo.LastWriteTimeUtc,
CreationTime = fileInfo.CreationTimeUtc
},
Path = path
};
_cache[path] = entry;
return read;
}
示例15: CreateDeletePackage
private static void CreateDeletePackage(int Sheets, int rows)
{
List<object> row = new List<object>();
row.Add(1);
row.Add("Some text");
row.Add(12.0);
row.Add("Some larger text that has completely no meaning. How much wood can a wood chuck chuck if a wood chuck could chuck wood. A wood chuck could chuck as much wood as a wood chuck could chuck wood.");
FileInfo LocalFullFileName = new FileInfo(Path.GetTempFileName());
LocalFullFileName.Delete();
package = new ExcelPackage(LocalFullFileName);
try
{
for (int ca = 0; ca < Sheets; ca++)
{
CreateWorksheet("Sheet" + (ca+1), row, rows);
}
package.Save();
}
finally
{
LocalFullFileName.Refresh();
if (LocalFullFileName.Exists)
{
LocalFullFileName.Delete();
}
package.Dispose();
package = null;
GC.Collect();
}
}