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); }
public NtStatus WriteFile(byte[] buffer, out int writtenBytes, long offset) { try { var(stream, streamFromCache) = GetStream(true); stream.Position = offset; writtenBytes = buffer.Length; stream.Write(buffer, 0, buffer.Length); stream.Flush(); file.Refresh(); FileInformation.Length = file.Length; if (!streamFromCache) { stream.Close(); } return(DokanResult.Success); } catch (FileNotFoundException e) { writtenBytes = 0; Console.WriteLine("DokanPBO::WriteFile failed due to FileNotFoundException: " + e); return(DokanResult.FileNotFound); } //#TODO access denied exception }
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(); } } }
/// <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; }
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."); }
private void RestoreGame(string backupName) { DebugLog("Restoring game " + backupName); string dirNameFull = new FileInfo(backupName).Name; Regex r = new Regex(@"^" + farmsimVersion + "_(savegame[0-9]+)_[0-9]{8}-[0-9]{6}.zip$"); Match m = r.Match(dirNameFull); DebugLog("dirNameFull " + dirNameFull); if (m.Success) { if (m.Groups[1].Value != null) { string dirName = m.Groups[1].Value; string mySaveGameDir = saveGamePath + Path.DirectorySeparatorChar + dirName; if (Directory.Exists(mySaveGameDir)) { DebugLog(dirName + " already exists!"); DialogResult result = MessageBox.Show(dirName + " already exists, overwrite?", "Overwrite Save?", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { // file system calls can be delayed so wait for folder to be deleted var fi = new System.IO.FileInfo(mySaveGameDir); if (fi.Exists) { Directory.Delete(mySaveGameDir, true); fi.Refresh(); while (fi.Exists) { System.Threading.Thread.Sleep(100); fi.Refresh(); } } } if (result == DialogResult.No) { return; } } Directory.CreateDirectory(mySaveGameDir); string zipFilePath = backupFolder + Path.DirectorySeparatorChar + backupName; DebugLog("Unzipping from " + zipFilePath); UnzipFile(zipFilePath, mySaveGameDir); GetSaveGames(); } else { DebugLog("Unable to determine save game folder name from " + dirNameFull); } DebugLog("RestoreGame complete"); } }
public void DeleteLock() { var fi = new System.IO.FileInfo(lockFile); if (fi.Exists) { fi.Delete(); fi.Refresh(); while (fi.Exists) { System.Threading.Thread.Sleep(100); fi.Refresh(); } } }
/// <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; }
/// <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; }
public async Task GenerateAudioAsync(VideoInfo video, System.IO.FileInfo Audiofile, AudioEncodingEnum AudioEncoding = AudioEncodingEnum.mp3, SoundTypeEnum Channels = SoundTypeEnum.Stereo, int AudioBitRate = 128, int AudioFrequency = 44100) { if (Audiofile.Exists) { Audiofile.Delete(); } var FNWE = video.File.FileNameWithoutExtension() + "_Audio"; var TempDirectory = new System.IO.DirectoryInfo(video.File.Directory.FullName + @"\.Temp\" + DateTime.Now.Year + DateTime.Now.Month.ToString("00") + DateTime.Now.Day.ToString("00")); if (!TempDirectory.Exists) { TempDirectory.Create(); } System.IO.FileInfo TempLogFile = new System.IO.FileInfo(TempDirectory.FullName + @"\" + FNWE + ".log"); if (TempLogFile.Exists) { TempLogFile.Delete(); } _logger.LogDebug("Grabbing Audio"); var LogData = await RunFFMpegAsync("-i \"" + video.File.FullName + "\" -vn -acodec " + AudioEncoding.AudioFormat() + " -ab " + AudioBitRate + "k -ac " + System.Convert.ToInt32(Channels) + " -ar " + AudioFrequency + " -y \"" + Audiofile.FullName + "\""); var SW = new System.IO.StreamWriter(TempLogFile.OpenWrite()); SW.Write(LogData); SW.Close(); if (EncodingState == EncodingStateEnum.Not_Encoding) { throw new Exception("No audio was encoded.\n\r" + LogData); } _logger.LogDebug("Audio Grabbed"); Audiofile.Refresh(); }
public async Task GenerateImageAsync(VideoInfo video, System.IO.FileInfo ImageFile, int Width, int Height) { if (ImageFile.Exists) { ImageFile.Delete(); } var FNWE = video.File.FileNameWithoutExtension() + "_Image"; var TempDirectory = new System.IO.DirectoryInfo(video.File.Directory.FullName + @"\.Temp\" + DateTime.Now.Year + DateTime.Now.Month.ToString("00") + DateTime.Now.Day.ToString("00")); if (!TempDirectory.Exists) { TempDirectory.Create(); } System.IO.FileInfo TempLogFile = new System.IO.FileInfo(TempDirectory.FullName + @"\" + FNWE + ".log"); if (TempLogFile.Exists) { TempLogFile.Delete(); } _logger.LogDebug("Grabbing Image"); var LogData = await RunFFMpegAsync("-i \"" + video.File.FullName + "\" -an -ss 00:00:07 -an -s " + Width + "x" + Height + " -r 1 -vframes 1 -f image2 -y \"" + ImageFile.FullName + "\""); var SW = new System.IO.StreamWriter(TempLogFile.OpenWrite()); SW.Write(LogData); SW.Close(); _logger.LogDebug("Image Grabbed"); ImageFile.Refresh(); }
public virtual void readMetadata(MediaProbe mediaProbe, Stream data, MetadataFactory.ReadOptions options, BaseMetadata media, CancellationToken token, int timeoutSeconds) { XMPLib.MetaData.ErrorCallbackDelegate errorCallbackDelegate = new XMPLib.MetaData.ErrorCallbackDelegate(errorCallback); //XMPLib.MetaData xmpMetaDataReader = new XMPLib.MetaData(errorCallbackDelegate, null); XMPLib.MetaData xmpMetaDataReader = new XMPLib.MetaData(null, null); try { FileInfo info = new FileInfo(media.Location); info.Refresh(); media.LastModifiedDate = info.LastWriteTime < sqlMinDate ? sqlMinDate : info.LastWriteTime; media.FileDate = info.CreationTime < sqlMinDate ? sqlMinDate : info.CreationTime; media.MimeType = MediaFormatConvert.fileNameToMimeType(media.Name); if (media.SupportsXMPMetadata == false) return; xmpMetaDataReader.open(media.Location, Consts.OpenOptions.XMPFiles_OpenForRead); readXMPMetadata(xmpMetaDataReader, media); } catch (Exception e) { Logger.Log.Error("Cannot read XMP metadata for: " + media.Location, e); media.MetadataReadError = e; } finally { xmpMetaDataReader.Dispose(); xmpMetaDataReader = null; } }
/// <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(); } } }
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(); }
public void NotifiesOfSegmentWhenFileIsCreated() { //need to make this test var file = Path.GetTempFileName(); var info = new FileInfo(file); var refresher = new Subject<Unit>(); var segmenter = new FileSegmenter(info.WatchFile(refresher), 1000); FileSegmentCollection result = null; using (var indexer = segmenter.Segments.Subscribe(segment => result = segment)) { result.Should().NotBeNull(); File.AppendAllLines(file, Enumerable.Range(1, 10000).Select(i => $"This is line number {i.ToString("00000000")}").ToArray()); refresher.Once(); result.Should().NotBeNull(); result.Count.Should().BeGreaterOrEqualTo(2); result.Segments.Select(fs => fs.Type).Should().Contain(FileSegmentType.Head); result.Segments.Select(fs => fs.Type).Should().Contain(FileSegmentType.Tail); result.FileLength.Should().Be(info.Length); File.AppendAllLines(file, Enumerable.Range(101, 10).Select(i => $"{i}")); refresher.Once(); info.Refresh(); result.FileLength.Should().Be(info.Length); File.Delete(file); } File.Delete(file); }
/// <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; }
public FileTelemetryConsumer(FileInfo file) { _logFileName = file.FullName; var fileExists = File.Exists(_logFileName); _logOutput = fileExists ? file.AppendText() : file.CreateText(); file.Refresh(); }
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"]); }
/// <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; }
/// <summary> /// Prepares data directory and obtains exclusive lock for the directory. /// </summary> /// <exception cref="LockFailedException"></exception> public SharedDataDirectory() { var dataDirPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), "AldursLab", "WurmAssistantData"); dataDir = new DirectoryInfo(dataDirPath); if (!dataDir.Exists) dataDir.Create(); var lockFile = new FileInfo(Path.Combine(dataDir.FullName, "app.lock")); if (!lockFile.Exists) { try { lockFile.Create().Dispose(); } catch (IOException) { // wait a moment to ensure file system is updated Thread.Sleep(100); lockFile.Refresh(); if (lockFile.Exists) { // ignore, something else created the lock file } else { throw; } } } appLock = FileLock.Enter(lockFile.FullName); }
public XmlFile(FileInfo file, bool create, string root_name) { this.File = file; file.Refresh(); if (!file.Exists) { if(create) { XmlTextWriter write_here = new XmlTextWriter(file.FullName, System.Text.Encoding.UTF8); write_here.Formatting = Formatting.Indented; write_here.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); //write_here.WriteStartElement(root_name); //write_here.WriteEndElement(); write_here.Close(); } else { throw new FileNotFoundException("XMl file not found",file.FullName); } } XmlReader parse_me = XmlReader.Create(file.FullName, xml_settings); try { this.Load(parse_me); } catch (Exception ex) { IXmlLineInfo info = parse_me as IXmlLineInfo; throw new XmlException(file.FullName + Environment.NewLine + Environment.NewLine + "Line: " + info.LineNumber + " Column: " + info.LinePosition, ex); } finally { parse_me.Close(); } }
public void MakeSureFileIsRight(string textToWrite) { FileInfo f = new FileInfo("MakeSureFileIsRight.txt"); if (f.Exists) { f.Delete(); } using (TextWriter writer = f.WriteTextIfNotDuplicate()) { writer.Write(textToWrite); writer.Close(); } f.Refresh(); Assert.IsTrue(f.Exists); using (TextReader reader = f.OpenText()) { if (textToWrite == null) { textToWrite = ""; } Assert.AreEqual(textToWrite, reader.ReadToEnd(), "Incorrect text came back"); } }
/// <summary> /// Copies a source file to a directory. Also copies over any "valid" includes we can find. /// </summary> /// <param name="sourceFile"></param> /// <param name="destDirectory"></param> public static FileInfo CopyToDirectory(FileInfo sourceFile, DirectoryInfo destDirectory) { /// /// See if the destination file is already there. If so, don't copy over /// FileInfo destFile = new FileInfo(destDirectory.FullName + "\\" + sourceFile.Name); if (destFile.Exists) { if (destFile.LastWriteTime >= sourceFile.LastWriteTime && destFile.Length == sourceFile.Length) { return destFile; } } sourceFile.CopyTo(destFile.FullName, true); /// /// Next, if there are any include files we need to move /// CopyIncludedFilesToDirectory(sourceFile, destDirectory); /// /// Return what we know! /// destFile.Refresh(); return destFile; }
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(); } }
public void Setup() { _file = new FileInfo(Path.Combine(@".\Resources", FileName)); _file.Refresh(); Assert.IsTrue(_file.Exists); _originalImage = Resources.silver_laptop_icon; }
private static void LosslessCompress(FileInfo file, bool progressive) { FileInfo output = new FileInfo(Path.GetTempFileName()); try { int result = NativeJpegOptimizer.Optimize(file.FullName, output.FullName, progressive); if (result == 1) throw new MagickCorruptImageErrorException("Unable to decompress the jpeg file.", null); if (result == 2) throw new MagickCorruptImageErrorException("Unable to compress the jpeg file.", null); if (result != 0) return; output.Refresh(); if (output.Length < file.Length) output.CopyTo(file.FullName, true); file.Refresh(); } finally { FileHelper.Delete(output); } }
public CompilationResult GetOrAdd(string filename, Func<string, CompilationResult> compilationDelegate, string mimeType) { var outputFileName = Path.Combine(_basePath, filename); FileInfo fi = new FileInfo(outputFileName); if (fi.Exists) { return new CompilationResult(true, File.ReadAllText(outputFileName), mimeType, fi.LastWriteTimeUtc); } var result = compilationDelegate(filename); try { File.WriteAllText(outputFileName, result.Contents); // XXX: Is this needed? fi.Refresh(); fi.LastWriteTimeUtc = result.SourceLastModifiedUtc; } catch (IOException) { // NB: If we get here, this means that two threads are trying to // write the file concurrently - just let the other one win, we will // later try to serve up the static file anyways // // TODO: Verify this :) } return result; }
/// <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; }
public TextureFileInfo( FileInfo _fileName ) { m_fileName = _fileName; m_fileName.Refresh(); m_timeStamp = m_fileName.LastWriteTime; ReadImageInfos(); }
public static IKeyPair Load(FileInfo file, IDataSerializer serializer) { file.Refresh(); if (!file.Exists) throw new FileNotFoundException("not found", file.FullName); return serializer.Deserialize<KeyPair>(File.ReadAllBytes(file.FullName)); }
public void Moving_To_Root_Directory_Should_Work() { targetPath = new FileInfo(Path.Combine(rootDirectory.FullName, "targetFoo")); Assert.False(targetPath.Exists); var target = provider.MoveFile(original, targetPath.FullName); targetPath.Refresh(); Assert.True(targetPath.Exists); }
private static bool DoesCacheMatch(FileInfo currentFile, FileMetadata storedMetadata) { currentFile.Refresh(); return currentFile.Length == storedMetadata.Length && currentFile.LastWriteTimeUtc == storedMetadata.LastWriteTime && currentFile.CreationTimeUtc == storedMetadata.CreationTime ; }
public static void DeleteFileSystemInfoWithSchedulingIfNecessary(FileSystemInfo info) { var isDirectory = (info.Attributes & FileAttributes.Directory) != 0; Exception exception; try { // We must recursively delete all the files and folders in the directory, because we // can't do a scheduled delete on a directory that isn't empty. if (isDirectory) { foreach (var file in new FileSystemEnumerator<FileSystemInfo>(info.FullName, info.FullName, "*", SearchOption.TopDirectoryOnly, new FileSystemInfoResultHandler())) { DeleteFileSystemInfoWithSchedulingIfNecessary(file); } // Now we can try deleting the directory new DirectoryInfo(info.FullName).Delete(true); } else { // Delete the file if it exists, ensuring that any read-only // flag is toggled off first to prevent exceptions. var file = new FileInfo(info.FullName); file.Refresh(); if (!file.Exists) return; file.IsReadOnly = false; file.Delete(); Trace.WriteLine("Successfully deleted file: " + file.FullName); } return; } catch (UnauthorizedAccessException uae) { exception = uae; } catch (IOException ioe) { switch (Marshal.GetHRForException(ioe)) { case -2147024894: // File doesn't exist return; } exception = ioe; } if (Win32Api.IO.MoveFileEx(info.FullName, null, Win32Api.IO.MoveFileFlags.DelayUntilReboot)) { Trace.WriteLine("Successfully scheduled deletion for file that is currently locked: " + info.FullName); return; } throw new InvalidOperationException(string.Format("Couldn't schedule delete of {0} '{1}' at reboot.", isDirectory ? "directory" : "file", Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error())), exception); }
public void Delete_File_OK() { _dummyFile = CreateFile(); var sut = new FileInfoProxy(_dummyFile.Name); Assert.DoesNotThrow(() => sut.Delete(), "Method failed, throwing an exception."); _dummyFile.Refresh(); Assert.IsFalse(_dummyFile.Exists); }
public void CreateTheFile_WhenItDoesNotExists() { // Arrange System.IO.FileInfo fileToResize = new System.IO.FileInfo(@"E:\Pst Backup\Test Files\FileToResize.pst"); // Act if (fileToResize.Exists) { fileToResize.Delete(); fileToResize.Refresh(); Assert.IsFalse(fileToResize.Exists); } SUT.ResizeFile(fileToResize.FullName, 4096L); fileToResize.Refresh(); // Assert Assert.IsTrue(fileToResize.Exists); Assert.AreEqual(4096L, fileToResize.Length); }
/// <summary> /// Initializes a new instance of the <see cref="FileViewSource"/> class. /// </summary> /// <param name="fileInfo">The file info.</param> public FileViewSource(FileInfo fileInfo) { fileInfo.Refresh(); if (!fileInfo.Exists) { throw new FileNotFoundException("FileNotFound", fileInfo.FullName); } _fileInfo = fileInfo; _lastUpdated = LastModified; }
public static void writeLine(string msg) { try { if (!logDirectory.Exists) { logDirectory.Create(); } if (file == null) { file = new FileInfo(string.Format(ApplicationPath + "\\Log\\{0:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now)); lock (objLock) { sw = file.CreateText(); } } if (!file.Exists) { file = new FileInfo(string.Format(ApplicationPath + "\\Log\\{0:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now)); lock (objLock) { sw = file.CreateText(); } } if (file.Length > logFileMaxSize) { sw.Flush(); if (sw != null) { sw.Close(); } sw.Dispose(); file = new FileInfo(string.Format(ApplicationPath + "\\Log\\{0:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now)); lock (objLock) { sw = file.CreateText(); } // sw.WriteLine(msg); } lock (objLock) { sw.WriteLine(msg); sw.AutoFlush = true; file.Refresh(); } // System.Windows.Forms.MessageBox.Show("sa","ss"); } catch (Exception e) { writeLine(e.ToString()); } }
public void ShrinkTheFile_WhenItIsTooLarge() { // Arrange System.IO.FileInfo fileToResize = new System.IO.FileInfo(@"E:\Pst Backup\Test Files\FileToResize.pst"); // Act if (fileToResize.Exists) { fileToResize.Delete(); fileToResize.Refresh(); Assert.IsFalse(fileToResize.Exists); } SUT.ResizeFile(fileToResize.FullName, 20000L); fileToResize.Refresh(); Assert.AreEqual(20000L, fileToResize.Length); SUT.ResizeFile(fileToResize.FullName, 4096L); fileToResize.Refresh(); // Assert Assert.AreEqual(4096L, fileToResize.Length); }
/// <summary> /// Checks if the file defined by the provided FileInfo exists. /// </summary> /// <param name="fInfo"></param> /// <returns>True if the file exists, false if it doesn't or the FileInfo is null</returns> public static bool FileExists(System.IO.FileInfo fInfo) { if (fInfo != null) { fInfo.Refresh(); return(fInfo.Exists); } else { return(false); } }
// delete the selected file called from deleteconfirmationpanel OK button. public void DeleteFile() { ContinuousSaveController.continuousSaveActive = false; FileInfo fi = new System.IO.FileInfo(dataPath + "/" + deleteName + ".dat"); UnityEngine.Debug.Log(fi); if (fi.Exists) { fi.Delete(); fi.Refresh(); while (fi.Exists) { System.Threading.Thread.Sleep(100); fi.Refresh(); } } DeleteFileCenterSnap deletecentersnap = FindObjectOfType <DeleteFileCenterSnap>(); deletecentersnap.StartRepopulate(dataPath); deleteConfirmPanel.SetActive(false); }
public void writeLine(string msg) { msg = string.Format("{0:yyyy-MM-dd HH:mm:ss.fffffff}", DateTime.Now) + msg; try { if (!logDirectory.Exists) { logDirectory.Create(); } if (file == null) { // file = new FileInfo(string.Format(logDirectory + "\\{0}_Host-{1:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now,IP)); file = new FileInfo(string.Format(logDirectory + "\\Host_{0}-{1:yyyy-MM-dd_HH-mm-ss}.txt", IP, DateTime.Now)); lock (objLock) { sw = file.CreateText(); } } if (!file.Exists) { file = new FileInfo(string.Format(logDirectory + "\\Host_{0}-{1:yyyy-MM-dd_HH-mm-ss}.txt", IP, DateTime.Now)); lock (objLock) { sw = file.CreateText(); } } if (file.Length > logFileMaxSize) { sw.Flush(); if (sw != null) { sw.Close(); } sw.Dispose(); file = new FileInfo(string.Format(logDirectory + "\\Host_{0}-{1:yyyy-MM-dd_HH-mm-ss}.txt", IP, DateTime.Now)); lock (objLock) { sw = file.CreateText(); } } lock (objLock) { sw.WriteLine(msg); sw.AutoFlush = true; file.Refresh(); } } catch (Exception e) { tools.log.Debug("writeLine方法异常:" + e.ToString()); } }
public void DownFileSync_file_exists_yes() { IO.FileInfo downloadedFile = new IO.FileInfo("C:\\temp\\Download\\" + Constants.Ftp.Files.File_1_1.Name); DownloaderFile df = new DownloaderFile(Constants.Ftp.Files.File_1_1, downloadedFile); df.StartDownload(async: false); downloadedFile.Refresh(); byte[] file_ftp = IO.File.ReadAllBytes(Constants.HDFtp.Files.File_1_1.FullName); byte[] file_hd = IO.File.ReadAllBytes(downloadedFile.FullName); Assert.IsTrue(downloadedFile.Exists); Assert.IsTrue(StructuralComparisons.StructuralEqualityComparer.Equals(file_ftp, file_hd)); }
public static void writeLine(string msg) { try { if (!logDirectory.Exists) { logDirectory.Create(); } if (file == null) { // System.Windows.Forms.MessageBox.Show(string.Format("c:\\{0:yyyy-MM-dd-HH:mm:ss}.log", DateTime.Now), "sss"); file = new FileInfo(string.Format(ApplicationPath + "\\Log\\{0:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now)); sw = file.CreateText(); sw.Dispose(); } file.Refresh(); // System.Windows.Forms.MessageBox.Show(file.Length.ToString(), "ss"); if (!file.Exists) { file = new FileInfo(string.Format(ApplicationPath + "\\Log\\{0:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now)); sw = file.CreateText(); sw.Dispose(); } if (file.Length > 1024 * 10240) { //System.Windows.Forms.MessageBox.Show("sa", "ss"); file = new FileInfo(string.Format(ApplicationPath + "\\Log\\{0:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now)); sw = file.CreateText(); sw.WriteLine(msg); } else { sw = file.AppendText(); } sw.WriteLine(msg); sw.Flush(); // System.Windows.Forms.MessageBox.Show("sa","ss"); } catch (Exception e) { tools.log.Debug(e.ToString()); } finally{ sw.Close(); sw.Dispose(); } }
public async Task <ActionResult> FileUpload() { string filePath = System.IO.Path.Combine(_hostingEnvironment.WebRootPath, _filePath); if (!System.IO.Directory.Exists(filePath)) { System.IO.Directory.CreateDirectory(filePath); } var file = Request.Form.Files.FirstOrDefault(); if (file == null) { throw new Abp.UI.UserFriendlyException(417, "没有图片"); } string fileType = file.FileName.Split(".").LastOrDefault(); string[] fileTypeArr = new string[] { "jpg", "gif", "png", "jpeg" }; if (string.IsNullOrEmpty(fileType) || !fileTypeArr.Contains(fileType.ToLower())) { throw new Abp.UI.UserFriendlyException(415, "非图片文件"); } string fileName = DateTime.Now.ToString("yyyyMMddHHmm_") + file.FileName; string fullFilePath = System.IO.Path.Combine(filePath, fileName); using (System.IO.FileStream fs = System.IO.File.Create(fullFilePath)) { await file.CopyToAsync(fs); await fs.FlushAsync(); } var savedFile = new System.IO.FileInfo(fullFilePath); var optimizer = new ImageOptimizer(); optimizer.Compress(savedFile); savedFile.Refresh(); return(Json(new { StatusCode = 200, Info = "图片上传成功!", Data = new { url = string.Format("{0}{1}/{2}{3}", "Http://", Request.Host, _filePath, fileName), name = fileName, } })); }
public void updateAppConfig(string key, string value) { init(); if (AppConfigfile.Exists) { AppConfigfile.Delete(); } sw = AppConfigfile.CreateText(); sw.WriteLine("<?xml version=\"" + "1.0\"?>"); sw.WriteLine("<configuration>"); sw.WriteLine("<connectionStrings>"); sw.WriteLine("<add name=\"Default\" connectionString=\"Max Pool Size = 512;server=" + "." + ";uid=sa; pwd=esun5005;database=ESUNNET\" providerName=\"System.Data.SqlClient\" />"); sw.WriteLine("</connectionStrings>"); sw.WriteLine(" <appSettings>"); if (key == "LeavePath") { sw.WriteLine("<add key=\"LeavePath\" value=\"" + value + "\"/>"); sw.WriteLine("<add key=\"RecordPath\" value=\"" + value + "\"/>"); } // sw.WriteLine("<add key=\"LeavePath\" value=\"" + "D:\\work\\z中百集团\\VXML" + "\"/>"); if (key == "RecordPath") { sw.WriteLine("<add key=\"LeavePath\" value=\"" + value + "\"/>"); sw.WriteLine("<add key=\"RecordPath\" value=\"" + value + "\"/>"); } sw.WriteLine("</appSettings>"); sw.WriteLine("</configuration>"); sw.AutoFlush = true; AppConfigfile.Refresh(); sw.Flush(); if (sw != null) { sw.Close(); } sw.Dispose(); }
public string creatFile() { if (!IISDirectory.Exists) { tools.log.Debug("iis路径不存在,请检查"); return("iis路径不存在,请检查"); } if (file == null) { file = new FileInfo(IISDirectory.ToString() + "\\callout" + e.taskID + ".html"); } try { if (file.Exists) { file.Delete(); } // sw = file.CreateText(); sw = new StreamWriter(file.FullName, false, Encoding.UTF8); // sw.WriteLine("<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"callOutDefault.aspx.cs\" Inherits=\"VXML.callOutDefault\" %><?xml version=\"1.0\" encoding=\"utf-8\" ?><vxml version=\"1.0\">"); sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?><vxml version=\"1.0\">"); sw.WriteLine("<var name = \"gRetryMaxTimes\" expr = \"3\" />"); sw.WriteLine("<var name = \"gRetryTimes\" expr = \"0\" />"); sw.WriteLine("<var name = \"gNoInputTimes\" expr = \"0\" />"); sw.WriteLine("<form id=\"start\">"); sw.WriteLine("<block><prompt><audio src = \"d:\\music\\welcome.wav\">您好,这里是江岸区监督指挥中心,你于</audio></prompt>"); // sw.WriteLine("<prompt>" + e.toIVRDay(e.dateTime.Trim()) + "</prompt> "); sw.WriteLine("<prompt><audio src = \"d:\\music\\mm" + e.toIVRMM(e.dateTime.Trim()) + ".wav\">" + e.toTTSMM(e.dateTime.Trim()) + "月</audio></prompt>"); sw.WriteLine("<prompt><audio src = \"d:\\music\\day" + e.toIVRDay(e.dateTime.Trim()) + ".wav\">" + e.toTTSDay(e.dateTime.Trim()) + "日</audio></prompt>"); // sw.WriteLine("<prompt><audio src = \"d:\\music\\guanyu.wav\">在</audio></prompt><prompt>" + e.accidentAddress + "</prompt>"); // sw.WriteLine("<prompt><audio src = \"d:\\music\\event.wav\">投诉的案件已处置完毕</audio></prompt>"); sw.WriteLine("<prompt><audio src = \"d:\\music\\menu.wav\"> 请您对该案件的处置结果进行评价。满意请按一,基本满意请按二,不满意请按三,谢谢.</audio></prompt> <goto next=\"#isAgain\" /></block> </form>"); sw.WriteLine("<menu id=\"isAgain\">"); sw.WriteLine("<choice dtmf = \"1\" next = \"#Digits1\"/>"); sw.WriteLine("<choice dtmf = \"2\" next = \"#Digits2\"/>"); sw.WriteLine("<choice dtmf = \"3\" next = \"#Digits3\"/>"); // sw.WriteLine(" <choice dtmf = \"9\" next =\"#Digits9\"/>"); sw.WriteLine("</menu>"); sw.WriteLine("<form id=\"Digits1\"><block><prompt><audio src = \"d:\\music\\thanks.wav\"> 蟹蟹</audio></prompt><assign name=\"result\" expr=\"1\"/>"); sw.WriteLine("<assign name=\"caseID1\" expr=\"'" + e.taskID + "'\"/>"); sw.WriteLine("<submit next=\"http://10.6.79.75:83/evaluationSuccess.aspx\" namelist =\"caseID1 result\"/> "); sw.WriteLine("<disconnect/> </block></form>"); sw.WriteLine("<form id=\"Digits2\"><block><prompt><audio src = \"d:\\music\\thanks.wav\">蟹蟹 </audio></prompt><assign name=\"result\" expr=\"2\"/>"); sw.WriteLine("<assign name=\"caseID1\" expr=\"'" + e.taskID + "'\"/>"); sw.WriteLine("<submit next=\"http://10.6.79.75:83/evaluationSuccess.aspx\" namelist =\"caseID1 result\"/> "); sw.WriteLine("<disconnect/> </block></form>"); sw.WriteLine("<form id=\"Digits3\"><block><prompt><audio src = \"d:\\music\\thanks.wav\">蟹蟹 </audio></prompt><assign name=\"result\" expr=\"3\"/>"); sw.WriteLine("<assign name=\"caseID1\" expr=\"'" + e.taskID + "'\"/>"); sw.WriteLine("<submit next=\"http://10.6.79.75:83/evaluationSuccess.aspx\" namelist =\"caseID1 result\"/> "); sw.WriteLine("<disconnect/> </block></form>"); sw.WriteLine("<form id=\"Digits77\"><block><prompt><audio src = \"d:\\music\\noinputlong.wav\">一直未按键,您未对处理结果做出评价,我们将按基本满意记录。 \r\n</audio></prompt><assign name=\"result\" expr=\"77\"/>"); sw.WriteLine("<assign name=\"caseID1\" expr=\"'" + e.taskID + "'\"/>"); sw.WriteLine("<submit next=\"http://10.6.79.75:83/evaluationSuccess.aspx\" namelist =\"caseID1 result\"/> "); sw.WriteLine("<disconnect/> </block></form>"); sw.WriteLine("<form id=\"Digits78\"><block><prompt><audio src = \"d:\\music\\nomatchmore.wav\">三次输入错误,您未对处理结果做出评价,我们将按基本满意记录。\r\n</audio></prompt><assign name=\"result\" expr=\"78\"/>"); sw.WriteLine("<assign name=\"caseID1\" expr=\"'" + e.taskID + "'\"/>"); sw.WriteLine("<submit next=\"http://10.6.79.75:83/evaluationSuccess.aspx\" namelist =\"caseID1 result\"/> "); sw.WriteLine("<disconnect/> </block></form>"); sw.WriteLine("<noinput>"); sw.WriteLine("<assign name = \"gNoInputTimes\" expr = \"gNoInputTimes+1\" />"); sw.WriteLine("<if cond = \"gNoInputTimes >= gRetryMaxTimes\">"); sw.WriteLine("<goto next=\"#Digits77\"/>"); sw.WriteLine("<else />"); sw.WriteLine("<prompt> <audio src = \"d:\\music\\noinput.wav\">您没有输入 \r\n</audio> </prompt><reprompt /></if> </noinput>"); sw.WriteLine("<nomatch> <assign name = \"gRetryTimes\" expr = \"gRetryTimes+1\" />"); sw.WriteLine("<if cond = \"gRetryTimes >= gRetryMaxTimes\">"); sw.WriteLine("<goto next=\"#Digits78\"/>"); sw.WriteLine("<else />"); sw.WriteLine("<prompt>"); sw.WriteLine("<audio src = \"d:\\music\\nomatch.wav\"> 您的选择不正确,请重新选择\r\n</audio> </prompt> <reprompt /> </if> </nomatch>"); sw.WriteLine("</vxml>"); sw.AutoFlush = true; file.Refresh(); sw.Flush(); } catch (Exception ex) { tools.log.Debug("创建文件IO异常:" + ex.ToString()); return("false"); } finally { if (sw != null) { sw.Close(); } sw.Dispose(); } return("success"); }
public static void WriteAllLines(this FileInfo file, string[] contents) { File.WriteAllLines(file.FullName, contents); file.Refresh(); }
public static void WriteAllLines(this FileInfo file, IEnumerable <string> contents, Encoding encoding) { File.WriteAllLines(file.FullName, contents, encoding); file.Refresh(); }
public static void WriteAllText(this FileInfo file, string contents, Encoding encoding) { File.WriteAllText(file.FullName, contents, encoding); file.Refresh(); }
public static string ReadAllText(this FileInfo file) { file.Refresh(); return(File.ReadAllText(file.FullName)); }
private void PerformUnitTest() { System.IO.FileInfo fiBefore = null; fiBefore = new System.IO.FileInfo(OuputFilePath); fiBefore.Refresh(); Process BuildProcess = new Process(); ProcessStartInfo BuildStartInfo = new ProcessStartInfo(); BuildStartInfo.CreateNoWindow = false; BuildStartInfo.UseShellExecute = false; BuildStartInfo.FileName = MSBuildExePath + " "; BuildStartInfo.Arguments = ProjectFilePath; BuildProcess.StartInfo = BuildStartInfo; BuildProcess.Start(); BuildProcess.WaitForExit(); System.IO.FileInfo fiAfter = null; fiAfter = new System.IO.FileInfo(OuputFilePath); fiAfter.Refresh(); if (fiBefore.LastWriteTime != fiAfter.LastWriteTime) { Process BuildUTProcess = new Process(); ProcessStartInfo BuildUTStartInfo = new ProcessStartInfo(); BuildUTStartInfo.CreateNoWindow = false; BuildUTStartInfo.UseShellExecute = false; BuildUTStartInfo.FileName = MSBuildExePath + " "; BuildUTStartInfo.Arguments = UTProjectFilePath; BuildUTProcess.StartInfo = BuildUTStartInfo; BuildUTProcess.Start(); BuildUTProcess.WaitForExit(); Process UnitTestProcess = new Process(); ProcessStartInfo UnitTestStartInfo = new ProcessStartInfo(); UnitTestStartInfo.CreateNoWindow = false; UnitTestStartInfo.UseShellExecute = false; UnitTestStartInfo.FileName = NunitConsoleExePath + " "; UnitTestStartInfo.Arguments = " /xml:" + XMLReportFilePath + " " + UnitTestLibraryPath; UnitTestProcess.StartInfo = UnitTestStartInfo; UnitTestProcess.Start(); UnitTestProcess.WaitForExit(); Process UnitTestReportProcess = new Process(); ProcessStartInfo UnitTestReportStartInfo = new ProcessStartInfo(); UnitTestReportStartInfo.CreateNoWindow = false; UnitTestReportStartInfo.UseShellExecute = false; UnitTestReportStartInfo.WindowStyle = ProcessWindowStyle.Maximized; UnitTestReportStartInfo.FileName = ReportUnitExePath + " "; HTMLReportFilePath = HTMLReportFolderPath + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".html"; UnitTestReportStartInfo.Arguments = XMLReportFilePath + " " + HTMLReportFilePath; UnitTestReportProcess.StartInfo = UnitTestReportStartInfo; UnitTestReportProcess.Start(); UnitTestReportProcess.WaitForExit(); UnitTestReportProcess.Dispose(); UnitTestReportProcess.Close(); Send("Kindly check the unit test report attached.", "Unit Test Report", "*****@*****.**", HTMLReportFilePath); } }
public void Load() { bool settingsLoaded = false; // If configuration file not exists then... var settingsFi = new System.IO.FileInfo(InitialFile.FullName); if (settingsFi.Exists) { while (true) { SettingsFile data; // Deserialize and load data. lock (saveReadFileLock) { try { data = Serializer.DeserializeFromXmlFile <SettingsFile>(InitialFile.FullName); if (data == null) { return; } Programs.Clear(); if (data.Programs != null) { // Make sure default settings have unique by file name. var distinctPrograms = data.Programs .GroupBy(p => p.FileName.ToLower()) .Select(g => g.First()) .ToList(); for (int i = 0; i < distinctPrograms.Count; i++) { Programs.Add(distinctPrograms[i]); } } Games.Clear(); if (data.Games != null) { // Make sure default settings have unique by file name. var distinctGames = data.Games .GroupBy(p => p.FileName.ToLower()) .Select(g => g.First()) .ToList(); for (int i = 0; i < distinctGames.Count; i++) { Games.Add(distinctGames[i]); } } Pads.Clear(); if (data.Pads != null) { for (int i = 0; i < data.Pads.Count; i++) { Pads.Add(data.Pads[i]); } } settingsLoaded = true; break; } catch (Exception) { var form = new MessageBoxForm(); var backupFile = InitialFile.FullName + ".bak"; form.StartPosition = FormStartPosition.CenterParent; var result = form.ShowForm( "User settings file has become corrupted.\r\n" + "Program must reset your user settings in order to continue.\r\n\r\n" + " Click [Yes] to reset your user settings and continue.\r\n" + " Click [No] if you wish to attempt manual repair.\r\n\r\n" + "Settings File: " + InitialFile.FullName, "Corrupt user settings of " + Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Error); if (result == DialogResult.Yes) { if (System.IO.File.Exists(backupFile)) { System.IO.File.Copy(backupFile, InitialFile.FullName, true); settingsFi.Refresh(); } else { System.IO.File.Delete(InitialFile.FullName); break; } } else { // Avoid the inevitable crash by killing application first. Process.GetCurrentProcess().Kill(); return; } } } } } // If settings failed to load then... if (!settingsLoaded) { var resource = EngineHelper.GetResource("x360ce_Games.xml.gz"); // If internal preset was found. if (resource != null) { var sr = new StreamReader(resource); var compressedBytes = default(byte[]); using (var memstream = new MemoryStream()) { sr.BaseStream.CopyTo(memstream); compressedBytes = memstream.ToArray(); } var bytes = EngineHelper.Decompress(compressedBytes); var xml = System.Text.Encoding.UTF8.GetString(bytes); var programs = Serializer.DeserializeFromXmlString <List <x360ce.Engine.Data.Program> >(xml); Programs.Clear(); for (int i = 0; i < programs.Count; i++) { Programs.Add(programs[i]); } } } // Check if current app doesn't exist in the list then... var currentFile = new System.IO.FileInfo(Application.ExecutablePath); var currentGame = Games.FirstOrDefault(x => x.FileName == currentFile.Name); if (currentGame == null) { // Add x360ce.exe var item = x360ce.Engine.Data.Game.FromDisk(currentFile.Name); var program = Programs.FirstOrDefault(x => x.FileName == currentFile.Name); item.LoadDefault(program); SettingsFile.Current.Games.Add(item); } else { currentGame.FullPath = currentFile.FullName; } }
/// <summary> /// Método sem recaptcha /// </summary> /// <param name="linhaDigitavel">Linha digitável do boleto</param> public static void Consultar(string cnpj, string id, string linhaDigitavel, string cpfCnpjPagador) { IWebDriver driver = null; try { //Trata linha digitável linhaDigitavel = linhaDigitavel.Replace(".", string.Empty).Replace(" ", string.Empty); #region Diretório / Arquivos DirectoryInfo directoryInfo = new System.IO.DirectoryInfo("Boletos"); if (!directoryInfo.Exists) { directoryInfo.Create(); } directoryInfo = new System.IO.DirectoryInfo(Path.Combine(directoryInfo.FullName, cnpj)); if (!directoryInfo.Exists) { directoryInfo.Create(); } directoryInfo = new System.IO.DirectoryInfo(Path.Combine(directoryInfo.FullName, string.Format("{0:yyyy-MM-dd}", DateTime.Now))); if (!directoryInfo.Exists) { directoryInfo.Create(); } FileInfo fileInfo = new System.IO.FileInfo(Path.Combine(directoryInfo.FullName, "Boletos.pdf")); if (fileInfo.Exists) { fileInfo.Delete(); } #endregion Diretório / Arquivo #region Chrome - Options if (ConfigurationManager.AppSettings["selenium_webdriver"] == "chrome") { OpenQA.Selenium.Chrome.ChromeDriverService chromeService = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService(); chromeService.HideCommandPromptWindow = true; chromeService.SuppressInitialDiagnosticInformation = true; OpenQA.Selenium.Chrome.ChromeOptions chromeOptions = new OpenQA.Selenium.Chrome.ChromeOptions(); chromeOptions.AddUserProfilePreference("download.default_directory", directoryInfo.FullName); chromeOptions.AddUserProfilePreference("download.prompt_for_download", false); chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true"); //Disable chromeOptions.AddArgument("disable-infobars"); //chromeOptions.AddArgument("headless");Utilizado para suprimir a exibição da janela do chrome driver = new OpenQA.Selenium.Chrome.ChromeDriver(chromeService, chromeOptions); } #endregion Chrome - Options #region Firefox - Options if (ConfigurationManager.AppSettings["selenium_webdriver"] == "firefox") { /* * Firefoz config options * * http://kb.mozillazine.org/About:config_entries#Browser. * */ //Create FireFox Service OpenQA.Selenium.Firefox.FirefoxDriverService firefoxService = OpenQA.Selenium.Firefox.FirefoxDriverService.CreateDefaultService(); firefoxService.HideCommandPromptWindow = true; firefoxService.SuppressInitialDiagnosticInformation = true; //Create FireFox Profile object OpenQA.Selenium.Firefox.FirefoxOptions firefoxOptions = new OpenQA.Selenium.Firefox.FirefoxOptions(); //Set location to store files after downloading. firefoxOptions.SetPreference("browser.download.folderList", 2); firefoxOptions.SetPreference("browser.helperApps.alwaysAsk.force", false); firefoxOptions.SetPreference("browser.download.manager.focusWhenStarting", false); firefoxOptions.SetPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false); firefoxOptions.SetPreference("pdfjs.disabled", true); firefoxOptions.SetPreference("browser.download.dir", directoryInfo.FullName); //Set Preference to not show file download confirmation dialogue using MIME types Of different file extension types. firefoxOptions.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf"); // Use this to disable Acrobat plugin for previewing PDFs in Firefox (if you have Adobe reader installed on your computer) firefoxOptions.SetPreference("plugin.scan.Acrobat", "99.0"); firefoxOptions.SetPreference("plugin.scan.plid.all", false); //Pass profile parameter In webdriver to use preferences to download file. driver = new OpenQA.Selenium.Firefox.FirefoxDriver(firefoxService, firefoxOptions); } #endregion Firefox - Options if (driver == null) { throw new Exception("WebDriver do Selenium não definido nas configurações"); } driver.Navigate().GoToUrl("https://www.itau.com.br/servicos/boletos/atualizar/"); //Aguarda processamento da página WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60)); //Textbox var elem = wait.Until(d => { try { var ele = d.FindElement(By.Id("representacaoNumerica")); return(ele.Displayed ? ele : null); } catch (UnhandledAlertException) { return(null); } catch (StaleElementReferenceException) { return(null); } catch (NoSuchElementException) { return(null); } }); //Preenche os dados da pesquisa driver.FindElement(By.Id("representacaoNumerica")).SendKeys(linhaDigitavel); driver.FindElement(By.Id("txtDocumentoSacado")).SendKeys(cpfCnpjPagador); driver.FindElement(By.Id("btnProximo")).Click(); //Aguarda System.Threading.Thread.Sleep(2500); //Acessa aba aerta driver.SwitchTo().Window(driver.WindowHandles.Last()); //Botão de cownload elem = wait.Until(d => { try { var ele = d.FindElement(By.Name("frmPDF")); return(ele.Displayed ? ele : null); } catch (UnhandledAlertException) { return(null); } catch (StaleElementReferenceException) { return(null); } catch (NoSuchElementException) { return(null); } }); //Download ((IJavaScriptExecutor)driver).ExecuteScript("javascript:document.frmPDF.submit();"); //Aguarda System.Threading.Thread.Sleep(3000); //Renomear fileInfo.Refresh(); if (fileInfo.Exists) { fileInfo.MoveTo(Path.Combine(directoryInfo.FullName, string.Format("{0}.pdf", id))); } } catch { throw; } finally { if (driver != null) { driver.Dispose(); } } }
public async Task <VideoInfo> ConvertToAsync(VideoInfo video, VideoConvertInfo newfile) { _logger.LogDebug("Converting Video"); DateTime STime = DateTime.Now; FileInfo FinalVideoFile = null; try { // Dim FInf = newfile.File //newfile.Duration = video.Duration; var FNWE = video.File.FileNameWithoutExtension(); var FNWE2 = ""; var TempDirectory = new System.IO.DirectoryInfo(video.File.Directory.FullName + @"\.Temp"); if (!TempDirectory.Exists) { TempDirectory.Create(); } _logger.LogDebug("Setting up file links"); if (newfile.File == null) { newfile.File = new System.IO.FileInfo(video.File.Directory.FullName + @"\" + FNWE + "." + newfile.VideoEncoding.ToString()); FNWE2 = FNWE; } else { FNWE2 = newfile.File.FileNameWithoutExtension(); } System.IO.FileInfo TempVideoFile = new System.IO.FileInfo(TempDirectory.FullName + @"\" + FNWE + newfile.File.Extension); // Dim TempImageFile As New System.IO.FileInfo(TempDirectory.FullName & "\" & FNWE & ".jpg") System.IO.FileInfo TempVideoLogFile = new System.IO.FileInfo(TempDirectory.FullName + @"\" + FNWE2 + "_" + newfile.VideoEncoding.ToString() + ".log"); // Dim TempImageLogFile As New System.IO.FileInfo(TempDirectory.FullName & "\" & FNWE & "-Img.log") FinalVideoFile = newfile.File; // Dim FinalImageFile As New System.IO.FileInfo(newfile.File.Directory.FullName & "\" & FNWE2 & ".jpg") if (TempVideoFile.Exists) { TempVideoFile.Delete(); } // If TempImageFile.Exists Then // TempImageFile.Delete() // End If if (TempVideoLogFile.Exists) { TempVideoLogFile.Delete(); } // If TempImageLogFile.Exists Then // TempImageLogFile.Delete() // End If if (newfile.Width == 0 && newfile.Height == 0) { newfile.Width = video.Width; newfile.Height = video.Height; } string AdditionalString = ""; _logger.LogDebug("Currently : " + video.Width + "x" + video.Height); _logger.LogDebug("Currently Adj: " + video.WidthAdjusted + "x" + video.HeightAdjusted); _logger.LogDebug("Going to : " + newfile.Width + "x" + newfile.Height); _logger.LogDebug("Going to Adj: " + newfile.WidthAdjusted + "x" + newfile.HeightAdjusted); var TopPad = 0; var BottomPad = 0; var LeftPad = 0; var RightPad = 0; if (!newfile.Stretch) { if (video.WidthAdjusted > 0 && video.HeightAdjusted > 0) { if ((newfile.WidthAdjusted / (double)video.WidthAdjusted) > (newfile.HeightAdjusted / (double)video.HeightAdjusted)) { // Y limited TopPad = 0; BottomPad = 0; var AF = newfile.WidthAdjusted - video.WidthAdjusted * (newfile.HeightAdjusted / (double)video.HeightAdjusted); var AF2 = System.Convert.ToInt32(AF / (double)2); if (AF2 % 2 > 0) { AF2 += 1; } LeftPad = AF2; RightPad = AF2; } else { // X Limited LeftPad = 0; RightPad = 0; var AF = newfile.HeightAdjusted - video.HeightAdjusted * (newfile.WidthAdjusted / (double)video.WidthAdjusted); var AF2 = System.Convert.ToInt32(AF / (double)2); if (AF2 % 2 > 0) { AF2 += 1; } TopPad = AF2; BottomPad = AF2; } if (TopPad > 0 || BottomPad > 0 || LeftPad > 0 || RightPad > 0) { if (newfile.VideoEncoding == VideoEncodingEnum.h264_iPod || newfile.VideoEncoding == VideoEncodingEnum.h264) { AdditionalString = " -padtop " + TopPad + " -padbottom " + BottomPad + " -padleft " + LeftPad + " -padright " + RightPad + " -padcolor 000000"; } else { AdditionalString = " -vf pad=" + RightPad + ":" + BottomPad + ":" + LeftPad + ":" + TopPad + ":000000"; } } } } _logger.LogDebug("Converting Video"); string LogData = ""; if (newfile.VideoEncoding == VideoEncodingEnum.flv) { List <TestRun> TestList = new List <TestRun>(); TestList.Add(new TestRun() { Quality = (int)newfile.QMax, Passes = newfile.NumberPasses, BitRate = newfile.BitRate, MaxQuality = (int)newfile.QMax + 5 }); if (newfile.QMax > 0) { var QT = (int)newfile.QMax; for (int a = 200; a <= 1000; a += 200) { TestList.Add(new TestRun() { Quality = QT, Passes = newfile.NumberPasses, BitRate = newfile.BitRate + a, MaxQuality = QT + 5 }); } for (int a = 0; a <= 1000; a += 200) { TestList.Add(new TestRun() { Quality = QT + 5, Passes = newfile.NumberPasses, BitRate = newfile.BitRate + a, MaxQuality = QT + 8 }); TestList.Add(new TestRun() { Quality = QT + 10, Passes = newfile.NumberPasses, BitRate = newfile.BitRate + a, MaxQuality = QT + 11 }); } TestList = (from TR in TestList orderby(Math.Pow(TR.MaxQuality, 2) + Math.Pow(TR.BitRate / 100.0, 2) * 0.65) select TR).ToList(); TestList.Add(new TestRun() { Quality = 0, Passes = PassEnum.Two, BitRate = newfile.BitRate + 1000, MaxQuality = 40 }); TestList.Add(new TestRun() { Quality = 0, Passes = PassEnum.One, BitRate = newfile.BitRate + 1000, MaxQuality = 40 }); } TempVideoFile.Refresh(); int Cnt = 0; _logger.LogDebug("TestList.Count=" + TestList.Count); while (((!TempVideoFile.Exists || TempVideoFile.Length < 1000) && (Cnt < TestList.Count))) { _logger.LogDebug("Cnt=" + Cnt + " Q=" + TestList[Cnt].Quality + " Passes=" + TestList[Cnt].Passes.ToString()); newfile.QMax = TestList[Cnt].Quality; newfile.NumberPasses = TestList[Cnt].Passes; newfile.BitRate = TestList[Cnt].BitRate; _logger.LogDebug("MaxQuality looking for=" + TestList[Cnt].MaxQuality); MaxQualityFound = 0; string Arguments = "-i \"" + video.File.FullName + "\" -r " + newfile.FrameRate + " -f flv " + (newfile.Deinterlace ? "-deinterlace " : "") + "-ac " + System.Convert.ToInt32(newfile.Channels) + " -ar " + newfile.AudioFrequency + " -ab " + newfile.AudioBitRate + "k" + (newfile.AudioEncoding != AudioEncodingEnum.None ? " -acodec " + newfile.AudioEncoding.AudioFormat() : "") + " -b " + newfile.BitRate + "k -s " + (newfile.WidthAdjusted - LeftPad - RightPad) + "x" + (newfile.HeightAdjusted - TopPad - BottomPad) + " -aspect 16:9 "; if (TestList[Cnt].Quality > 0) { Arguments = Arguments + "-qmin " + newfile.QMin + " -qmax " + newfile.QMax + " -qcomp 0.7 -g 299.7 -qdiff 4 "; } Arguments = Arguments + (AdditionalString + (video.IsAudio ? " -vn" : "")); if (newfile.NumberPasses == PassEnum.Two) { MaxQualityFound = 0; StartConversion?.Invoke(PassEnum.Two, 1); LogData = await RunFFMpegAsync("-pass 1 " + Arguments + " -y \"" + TempVideoFile.FullName + "\""); EndConversion?.Invoke(); MaxQualityFound = 0; StartConversion?.Invoke(PassEnum.Two, 2); LogData = await RunFFMpegAsync("-pass 2 " + Arguments + " -y \"" + TempVideoFile.FullName + "\""); EndConversion?.Invoke(); if (EncodingState == EncodingStateEnum.Not_Encoding) { } } else { MaxQualityFound = 0; StartConversion?.Invoke(PassEnum.One, 1); LogData = await RunFFMpegAsync(Arguments + " -y \"" + TempVideoFile.FullName + "\""); //newfile.EncodingState = video.EncodingState; EndConversion?.Invoke(); if (EncodingState == EncodingStateEnum.Not_Encoding) { throw new Exception("Nothing was encoded.\n\r" + LogData); } } Cnt += 1; TempVideoFile.Refresh(); _logger.LogDebug("MaxQualityFound=" + MaxQualityFound); _logger.LogDebug("TempVideoFile.Exists=" + TempVideoFile.Exists); if (MaxQualityFound > (TestList[Cnt - 1].MaxQuality) && TempVideoFile.Exists && TempVideoFile.Length > 1000 && Cnt < TestList.Count) { _logger.LogDebug("Video Created but not good enough quality"); TempVideoFile.Delete(); TempVideoFile.Refresh(); } TempVideoLogFile.Refresh(); if (TempVideoLogFile.Exists) { TempVideoLogFile.Delete(); } var SW2 = new System.IO.StreamWriter(TempVideoLogFile.OpenWrite()); SW2.Write(LogData); SW2.Close(); TempVideoLogFile.Refresh(); _logger.LogDebug(""); } _logger.LogDebug("TempVideoFile.Exists=" + TempVideoFile.Exists); } else if (newfile.VideoEncoding == VideoEncodingEnum.h264) { MaxQualityFound = 0; StartConversion?.Invoke(PassEnum.One, 1); var task = RunFFMpegOldAsync("-i \"" + video.File.FullName + "\" -r " + newfile.FrameRate + " -vcodec libx264 -threads 0 " + (newfile.Deinterlace ? "-deinterlace " : "") + "-ac " + System.Convert.ToInt32(newfile.Channels) + " -ar " + newfile.AudioFrequency + " -ab " + newfile.AudioBitRate + "k" + (newfile.AudioEncoding != AudioEncodingEnum.None ? " -acodec " + newfile.AudioEncoding.AudioFormat() : "") + " -s " + (newfile.WidthAdjusted - LeftPad - RightPad) + "x" + (newfile.HeightAdjusted - TopPad - BottomPad) + " -aspect 16:9 " + AdditionalString + (video.IsAudio ? " -vn" : "") + " -level 41 -crf 20 -bufsize 20000k -maxrate 25000k -g 250 -coder 1 -flags +loop -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -flags2 +dct8x8+bpyramid -me_method umh -subq 7 -me_range 16 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -rc_eq 'blurCplx^(1-qComp)' -bf 16 -b_strategy 1 -bidir_refine 1 -refs 6 -deblockalpha 0 -deblockbeta 0 -y \"" + TempVideoFile.FullName + "\""); _logger.LogDebug("ConvertTo - Awaiting Finishing of Convert"); LogData = await task; _logger.LogDebug("ConvertTo - Convert Finished"); //newfile.EncodingState = video.EncodingState; EndConversion?.Invoke(); if (EncodingState == EncodingStateEnum.Not_Encoding) { throw new Exception("Nothing was encoded.\n\r" + LogData); } } else if (newfile.VideoEncoding == VideoEncodingEnum.h264_iPod) { newfile.MaxQualityFound = 0; StartConversion?.Invoke(PassEnum.One, 1); LogData = await RunFFMpegOldAsync("-i \"" + video.File.FullName + "\" -r " + newfile.FrameRate + " -vcodec libx264 -threads 0 " + (newfile.Deinterlace ? "-deinterlace " : "") + "-ac " + System.Convert.ToInt32(newfile.Channels) + " -ar " + newfile.AudioFrequency + " -ab " + newfile.AudioBitRate + "k" + (newfile.AudioEncoding != AudioEncodingEnum.None ? " -acodec " + newfile.AudioEncoding.AudioFormat() : "") + " -s " + (newfile.WidthAdjusted - LeftPad - RightPad) + "x" + (newfile.HeightAdjusted - TopPad - BottomPad) + " -aspect " + (newfile.WidthAdjusted) + ":" + (newfile.HeightAdjusted) + " " + AdditionalString + (video.IsAudio ? " -vn" : "") + " -vpre \"" + Core.FFMpegLocation + @"ffpresets\libx264-ipod640.ffpreset"" -b " + newfile.BitRate + "k -bt " + newfile.BitRate + "k -f ipod -y \"" + TempVideoFile.FullName + "\""); //newfile.EncodingState = video.EncodingState; EndConversion?.Invoke(); if (EncodingState == EncodingStateEnum.Not_Encoding) { throw new Exception("Nothing was encoded.\n\r" + LogData); } } else if (newfile.VideoEncoding == VideoEncodingEnum.OGG_Theora) { // -f ogg -vcodec libtheora -b 800k -g 300 -acodec libvorbis -ab 128k string Arguments = "-i \"" + video.File.FullName + "\" -threads 0 -g 300 " + "-qmin " + newfile.QMin + " -qmax " + newfile.QMax + (newfile.Deinterlace ? " -deinterlace " : "") + " -ac " + System.Convert.ToInt32(newfile.Channels) + " -vcodec libtheora -acodec libvorbis -ab 128k -b 800k -s " + (newfile.WidthAdjusted - LeftPad - RightPad) + "x" + (newfile.HeightAdjusted - TopPad - BottomPad) + " -aspect 16:9 "; MaxQualityFound = 0; StartConversion?.Invoke(PassEnum.Two, 1); LogData = await RunFFMpegAsync("-pass 1 " + Arguments + " -y \"" + TempVideoFile.FullName + "\""); //newfile.EncodingState = EncodingState; EndConversion?.Invoke(); MaxQualityFound = 0; StartConversion?.Invoke(PassEnum.Two, 2); LogData = await RunFFMpegAsync("-pass 2 " + Arguments + " -y \"" + TempVideoFile.FullName + "\""); //newfile.EncodingState = EncodingState; EndConversion?.Invoke(); if (EncodingState == EncodingStateEnum.Not_Encoding) { throw new Exception("Nothing was encoded.\n\r" + LogData); } } else if (newfile.VideoEncoding == VideoEncodingEnum.WebM) { string Arguments = "-i \"" + video.File.FullName + "\" -threads 0 -keyint_min 0 -g 250 -skip_threshold 0 " + "-qmin " + newfile.QMin + " -qmax " + newfile.QMax + (newfile.Deinterlace ? " -deinterlace " : "") + " -ac " + System.Convert.ToInt32(newfile.Channels) + " -vcodec libvpx -acodec libvorbis -b 614400 -s " + (newfile.WidthAdjusted - LeftPad - RightPad) + "x" + (newfile.HeightAdjusted - TopPad - BottomPad) + " -aspect 16:9 "; MaxQualityFound = 0; StartConversion?.Invoke(PassEnum.Two, 1); LogData = await RunFFMpegAsync("-pass 1 " + Arguments + " -y \"" + TempVideoFile.FullName + "\""); //newfile.EncodingState = EncodingState; EndConversion?.Invoke(); MaxQualityFound = 0; StartConversion?.Invoke(PassEnum.Two, 2); LogData = await RunFFMpegAsync("-pass 2 " + Arguments + " -y \"" + TempVideoFile.FullName + "\""); //EncodingState = EncodingState; EndConversion?.Invoke(); if (EncodingState == EncodingStateEnum.Not_Encoding) { throw new Exception("Nothing was encoded.\n\r" + LogData); } } newfile.MaxQualityFound = MaxQualityFound; _logger.LogDebug("Video Converted"); TempVideoFile.Refresh(); if (TempVideoLogFile.Exists) { TempVideoLogFile.Delete(); } var SW = new System.IO.StreamWriter(TempVideoLogFile.OpenWrite()); SW.Write(LogData); SW.Close(); TempVideoLogFile.Refresh(); if (newfile.VideoEncoding == VideoEncodingEnum.flv) { _logger.LogDebug("Setting Meta Data"); LogData = await RunFLVToolAsync("-Uk \"" + TempVideoFile.FullName + "\""); } if (!FinalVideoFile.Directory.Exists) { FinalVideoFile.Directory.Create(); } _logger.LogDebug("Handling Temp Video File"); bool AllOK = true; if (TempVideoFile.Exists && TempVideoFile.Length > 1000) { FinalVideoFile.Refresh(); if (FinalVideoFile.Exists) { FinalVideoFile.Delete(); FinalVideoFile.Refresh(); } if (!FinalVideoFile.Exists) { TempVideoFile.MoveTo(FinalVideoFile.FullName); } else { _logger.LogDebug("FINAL VIDEO FILE still exists"); } } else { AllOK = false; } _logger.LogDebug("Cleaning up directory"); if (AllOK) { var HisDir = new System.IO.DirectoryInfo(video.File.Directory.FullName + @"\.Temp\" + DateTime.Now.Year + DateTime.Now.Month.ToString("00") + DateTime.Now.Day.ToString("00")); if (!HisDir.Exists) { HisDir.Create(); } System.IO.FileInfo FF; FF = new System.IO.FileInfo(HisDir.FullName + @"\" + TempVideoLogFile.Name); if (FF.Exists) { FF.Delete(); } TempVideoLogFile.MoveTo(FF.FullName); } } catch (Exception ex) { _logger.LogError(ex, ex.ToString()); throw; } _logger.LogDebug("Time to convert:" + (DateTime.Now.Subtract(STime).TotalMilliseconds / 1000)); Debug.WriteLine(DateTime.Now.Subtract(STime).TotalMilliseconds / 1000); return(new VideoInfo(FinalVideoFile)); }
public static void WriteAllBytes(this FileInfo file, byte[] bytes) { File.WriteAllBytes(file.FullName, bytes); file.Refresh(); }
public static void SetHidden(this FileInfo file, bool value) { file.Refresh(); SetAttribute(file, FileAttributes.Hidden, value); }
public static FileMime GetMimeType(this FileInfo file) { file.Refresh(); return(FileMime.Lookup(file)); }
public static byte[] ReadAllBytes(this FileInfo file) { file.Refresh(); return(File.ReadAllBytes(file.FullName)); }
public static string[] ReadAllLines(this FileInfo file) { file.Refresh(); return(File.ReadAllLines(file.FullName)); }