private static void SetButtonsClickEvents(Button save, Button cancel, Views.DialogWindow dialogWindow, TextBox fileName, TextBox extension, CheckBox hidden, string path) { cancel.Click += delegate { dialogWindow.Close(); }; save.Click += delegate { FileInfo fileInfo = new FileInfo(path); FileSecurity fileSecurity = fileInfo.GetAccessControl(); string user = System.Environment.UserName; fileSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl, AccessControlType.Allow)); fileInfo.SetAccessControl(fileSecurity); FileProperties file = new FileProperties() { CheckboxName = fileInfo.FullName, FileName = fileInfo.Name, CreatedTime = fileInfo.CreationTime, Size = System.String.Format("{0}KB", fileInfo.Length / 1024), }; file.GetFileName(path); file.SetExtension(extension.Text, path); if (hidden.IsChecked == true) { file.isHidden = true; } else { file.isHidden = false; } file.HideFile(path); file.ChangeName(fileName.Text, path); dialogWindow.Close(); }; }
/// <summary> /// 获取文件夹属性,信息还是FileProperties里的东西。 /// </summary> /// <param name="fullName">文件全名</param> /// <returns>文件夹属性</returns> public static FileProperties GetDirectoryProperty(string fullName) { FileProperties fpro = new FileProperties(); try { DirectoryInfo dirInfo = new DirectoryInfo(fullName); fpro.Attributies = dirInfo.Attributes.ToString(); fpro.CreationTime = dirInfo.CreationTime.ToString(); fpro.Extension = dirInfo.Extension; fpro.LastAccessTime = dirInfo.LastAccessTime.ToString(); fpro.LastWriteTime = dirInfo.LastWriteTime.ToString(); fpro.Length = ""; fpro.Name = dirInfo.Name; } catch { fpro.Attributies = ""; fpro.CreationTime = ""; fpro.Extension = ""; fpro.LastAccessTime = ""; fpro.LastWriteTime = ""; fpro.Length = ""; fpro.Name = ""; } return(fpro); }
public DownloadEntryViewModel(FileProperties file) { _file = file; Downloader = new Downloader(file); Downloader.PropertyChanged += OnDownloaderPropertyChanged; Downloader.Start(); }
/*************************** * My Files populate data ***************************/ private void PopulateMyFiles(object sender, MouseButtonEventArgs e) { VersionCol.Visibility = Visibility.Visible; InMyFiles = true; SidebarReviseButton.Visibility = Visibility.Visible; DatabaseCon con = new DatabaseCon(); con.OpenConnection(); List <string> paths = FileData.GetMyFilePath(); DataGridController data = new DataGridController(); ObservableCollection <FileAndDirAttributes> GridData = new ObservableCollection <FileAndDirAttributes>(); FileProperties file; if (paths.Count > 0) { foreach (string dir in paths) { file = new FileProperties(dir); GridData.Add(new FileAndDirAttributes { Type = false, FileIcon = "/Resources/Icons/file.png", FileName = file.GetFileName(), FileSize = file.GetFileSize(), FileDirectory = file.GetDirectory(), FileCreated = file.GetFileCreated(), FileAccessed = file.GetFileLastAccess(), FileModified = file.GetFileLastModify(), Versions = FileData.VersionCount(dir) }); } DirsAndFiles.ItemsSource = GridData; items.Content = (GridData.Count - 1) + " items"; size.Content = "No file selected."; } else { MessageBox.Show("Error", "No file found!"); } }
public async void ExportFile() { Console.WriteLine(_selectedIndex); string extension = FileProperties.GetExtension(GDAT.Files[_selectedIndex].Magic); SaveFileDialog dialog = new SaveFileDialog() { Title = "Where do you want to save this file !", DefaultExtension = extension, InitialFileName = _selectedIndex.ToString() + "." + extension }; IClassicDesktopStyleApplicationLifetime classicDesktopLifetime = (IClassicDesktopStyleApplicationLifetime)Application.Current.ApplicationLifetime; string results = await dialog.ShowAsync(classicDesktopLifetime.MainWindow); if (results == null) { return; } else { Console.WriteLine("Test"); GDATFile file = GDAT.Files[_selectedIndex]; using (FileStream s = File.Create(results)){ file.Export(s); } } }
/* Private methods */ private Gtk.Dialog BuildDialog() { FileProperties properties = Base.Document.TextFile; Gtk.Dialog dialog = new Gtk.Dialog(Catalog.GetString("File Properties"), Base.Ui.Window, DialogFlags.Modal | DialogFlagsUseHeaderBar); Grid grid = new Grid(); grid.BorderWidth = WidgetStyles.BorderWidthLarge; grid.ColumnSpacing = WidgetStyles.ColumnSpacingLarge; grid.RowSpacing = WidgetStyles.RowSpacingLarge; grid.Attach(CreateFieldLabel(Catalog.GetString("File Name")), 0, 0, 1, 1); grid.Attach(CreateValueLabel(properties.Filename), 1, 0, 1, 1); grid.Attach(CreateFieldLabel(Catalog.GetString("Path")), 0, 1, 1, 1); grid.Attach(CreateValueLabel(properties.Directory), 1, 1, 1, 1); grid.Attach(CreateFieldLabel(Catalog.GetString("Character Encoding")), 0, 2, 1, 1); grid.Attach(CreateValueLabel(GetEncoding(properties.Encoding)), 1, 2, 1, 1); grid.Attach(CreateFieldLabel(Catalog.GetString("Subtitle Format")), 0, 3, 1, 1); grid.Attach(CreateValueLabel(GetSubtitleFormat(properties.SubtitleType)), 1, 3, 1, 1); grid.Attach(CreateFieldLabel(Catalog.GetString("Timing Mode")), 0, 4, 1, 1); grid.Attach(CreateValueLabel(properties.TimingMode.ToString()), 1, 4, 1, 1); dialog.ContentArea.Add(grid); dialog.ContentArea.ShowAll(); return(dialog); }
/// <summary> /// 生成缩略图 /// </summary> /// <param name="imagefilePath">图片路径</param> /// <param name="timming">生成方式</param> public static void HandleThumbnail(string imagefilePath, ThumbnailTimming timming) { FileProperties _fileInfo = FileHelper.GetFileInfo(imagefilePath, @"^(.*)\\upload\\(.+)\\(day_\d+)\\(\d+)(\.[A-Za-z]+)$"); if (_fileInfo == null) { return; } string _root = _fileInfo.Root, _folder = _fileInfo.Folder, _subFolder = _fileInfo.SubFolder, _fileName = _fileInfo.FileName, _fileExt = _fileInfo.FileNameExt; foreach (var pair in UploadConfigContext.ThumbnailConfigDic .Where(t => t.Key.StartsWith(_fileInfo.Folder.ToLower() + "_", StringComparison.OrdinalIgnoreCase) && t.Value.Timming == timming)) { ThumbnailSize _size = pair.Value; string _thumbnailFileFolder = string.Format("{0}\\upload\\{1}\\{2}\\thumb", _root, _folder, _subFolder); if (!Directory.Exists(_thumbnailFileFolder)) { Directory.CreateDirectory(_thumbnailFileFolder); } string _thumbnailFilePath = string.Format("{0}\\upload\\{1}\\{2}\\thumb\\{3}_{4}_{5}{6}", _root, _folder, _subFolder, _fileName, _size.Width, _size.Height, _fileExt); ThumbnailHelper.BuilderThumbnail(imagefilePath, _thumbnailFilePath, _size); } }
public List <FileProperties> GetAllFiles(string FolderPath) { var items = new List <FileProperties>(); try { foreach (string dir in Directory.GetFiles(FolderPath)) { FileInfo _dirinfo = new FileInfo(dir); FileProperties file = new FileProperties() { CheckboxName = _dirinfo.FullName, FileName = _dirinfo.Name, CreatedTime = _dirinfo.CreationTime, Size = System.String.Format("{0}KB", _dirinfo.Length / 1024), }; items.Add(file); file.GetFileName(_dirinfo.FullName); } return(items); } catch (System.UnauthorizedAccessException) { return(null); } }
protected override void OnNavigatedTo(NavigationEventArgs e) { ViewModel = new SelectedItemsPropertiesViewModel(); var np = e.Parameter as Properties.PropertyNavParam; if (np.navParameter is ListedItem) { var listedItem = np.navParameter as ListedItem; if (listedItem.PrimaryItemAttribute == StorageItemTypes.File) { BaseProperties = new FileProperties(ViewModel, np.tokenSource, Dispatcher, null, listedItem); } else if (listedItem.PrimaryItemAttribute == StorageItemTypes.Folder) { BaseProperties = new FolderProperties(ViewModel, np.tokenSource, Dispatcher, listedItem); } } else if (np.navParameter is List <ListedItem> ) { BaseProperties = new CombinedProperties(ViewModel, np.tokenSource, Dispatcher, np.navParameter as List <ListedItem>); } else if (np.navParameter is DriveItem) { BaseProperties = new DriveProperties(ViewModel, np.navParameter as DriveItem); } base.OnNavigatedTo(e); }
/* Used in the object construction */ private void Open(string path, Encoding encoding) { SubtitleFactory factory = new SubtitleFactory(); factory.Encoding = encoding; factory.FallbackEncoding = GetFallbackEncoding(); factory.InputFrameRate = Base.Ui.Menus.TimingsInputFrameRateActive; SubLib.Core.Domain.Subtitles openedSubtitles = null; try { openedSubtitles = factory.Open(path); } catch (FileNotFoundException) { New(path); return; } subtitles = new Ui.View.Subtitles(openedSubtitles); textFile = factory.FileProperties; if (textFile.SubtitleType != SubtitleType.Unknown) { canTextBeSaved = true; } }
public void ReadFilePropertiesTest(string TestDataFolder) { string TestFile1Path = Path.Combine(TestDataFolder, "TestFile1.mp3"); FilePropertiesReader fpr = new FilePropertiesReader(TestDataFolder); // test for file properties List <FileProperties> files = fpr.GetFiles(); List <FileProperties> test_file_in_list = files.Where(file => file.Path == TestFile1Path).ToList(); Assert.AreEqual(1, test_file_in_list.Count, $"Not found: {TestFile1Path}"); FileProperties test_file = test_file_in_list.First(); Assert.IsFalse(test_file.IsDirectory, "GetFiles returned a directory"); Assert.AreEqual("Silence", test_file.Title, "Invalid title"); Assert.AreEqual("omccully", test_file.AnyArtist, "Invalid artist"); Assert.AreEqual("Not Applicable", test_file.Album, "Invalid album"); Assert.AreEqual("1", test_file.TrackNumber, "Invalid track number"); // test for GetFilesAndDirectories seeing the TestFolder string TestFolderFullPath = Path.Combine(TestDataFolder, "TestFolder"); List <FileProperties> directories = fpr.GetFilesAndDirectories().Where(f => f.IsDirectory).ToList(); Assert.AreEqual(1, directories.Count(d => d.Path == TestFolderFullPath), "Directory count incorrect. " + $"Expected: {TestFolderFullPath}\nDirectories found:\n" + String.Join("\n", directories)); }
public void OpenTranslation(string path, Encoding encoding) { if (this.IsTranslationLoaded) { CloseTranslation(); } SubtitleFactory factory = new SubtitleFactory(); factory.Encoding = encoding; factory.FallbackEncoding = GetFallbackEncoding(); SubLib.Core.Domain.Subtitles openedTranslation = factory.Open(path); FileProperties newTranslationFile = factory.FileProperties; AddExtraSubtitles(openedTranslation); Translations translations = new Translations(); translations.Import(subtitles, openedTranslation, Base.Config.TimingsTimeBetweenSubtitles); if (newTranslationFile.SubtitleType != SubtitleType.Unknown) { canTranslationBeSaved = true; } this.translationFile = newTranslationFile; this.isTranslationLoaded = true; }
private Subtitles EmptySubtitles(string path) { Subtitles subtitles = New(); fileProperties = new FileProperties(path, Encoding.UTF8, SubtitleType.Unknown, TimingMode.Times); return(subtitles); }
private static FileProperties GetFileProperties() { try { FileProperties fileprops = new FileProperties(); while (true) { SaveFileDialog savedialog = new SaveFileDialog() { CheckFileExists = false, DefaultExt = ".txt", Filter = "Text Files | *.txt", Title = "BOTW Randomized Splits" }; savedialog.FileName = "botw_randomized_splits"; System.Windows.Forms.DialogResult response = savedialog.ShowDialog(); if (response.Equals(System.Windows.Forms.DialogResult.OK)) { fileprops.Name = Path.GetFileName(savedialog.FileName); fileprops.Path = Path.GetDirectoryName(savedialog.FileName) + "\\"; } else { return(null); } if (CheckFileLock(savedialog.FileName) == true) { System.Windows.Forms.MessageBox.Show("Selected file open for editing" + System.Environment.NewLine + "Close file or select new filename", "BastianCAD Extract", MessageBoxButtons.OK); } else { return(fileprops); } } } catch (System.Exception ex) { System.Diagnostics.Debug.Print(ex.Message); } return(null); }
public void FileProtocolPutFileCloudAnonAsync() { FileProperties properties = new FileProperties(); cloudAnonAsync.PutFileScenarioTest(cloudSetup.ShareName, Guid.NewGuid().ToString(), properties, new byte[0], HttpStatusCode.NotFound); }
/// <summary> /// 获取文件属性 /// </summary> /// <param name="fullName">文件全名</param> /// <returns>文件属性</returns> public static FileProperties GetFileProperty(string fullName) { FileProperties fpro = new FileProperties(); try { FileInfo fileInfo = new FileInfo(fullName); fpro.Attributies = fileInfo.Attributes.ToString(); fpro.CreationTime = fileInfo.CreationTime.ToString(); fpro.Extension = fileInfo.Extension; fpro.LastAccessTime = fileInfo.LastAccessTime.ToString(); fpro.LastWriteTime = fileInfo.LastWriteTime.ToString(); fpro.Length = Deal.FormatFileLength(fileInfo.Length); fpro.Name = fileInfo.Name; } catch { fpro.Attributies = ""; fpro.CreationTime = ""; fpro.Extension = ""; fpro.LastAccessTime = ""; fpro.LastWriteTime = ""; fpro.Length = ""; fpro.Name = ""; } return(fpro); }
private void ChangeDates() { // Create empty DateTimes DateTime creationTime; DateTime modificationTime; DateTime lastAccessTime; try { // Try to parse the inputs to DateTimes creationTime = DateTime.Parse(CreationTime); modificationTime = DateTime.Parse(ModificationTime); lastAccessTime = DateTime.Parse(LastAccessTime); } catch { // Otherwise set an errormessage to the output ApplyOutput = "Please enter a valid date"; // And exit the function return; } // Set the times var isSuccess = FileProperties.SetTimes(creationTime, modificationTime, lastAccessTime, FullPath); // Set the output ApplyOutput = isSuccess ? "The times of the file have been changed successfully" : "Something went wrong. Please try again."; }
/// <summary> /// Gets the file's properties from the response. /// </summary> /// <param name="response">The web response.</param> /// <returns>The file's properties.</returns> public static FileProperties GetProperties(HttpWebResponse response) { CommonUtility.AssertNotNull("response", response); FileProperties properties = new FileProperties(); properties.ETag = HttpResponseParsers.GetETag(response); #if WINDOWS_PHONE properties.LastModified = HttpResponseParsers.GetLastModified(response); properties.ContentLanguage = response.Headers[Constants.HeaderConstants.ContentLanguageHeader]; #else properties.LastModified = response.LastModified.ToUniversalTime(); properties.ContentLanguage = response.Headers[HttpResponseHeader.ContentLanguage]; #endif properties.ContentDisposition = response.Headers[Constants.HeaderConstants.ContentDispositionResponseHeader]; properties.ContentEncoding = response.Headers[HttpResponseHeader.ContentEncoding]; // For range gets, only look at 'x-ms-content-md5' for overall MD5 if (response.Headers[HttpResponseHeader.ContentRange] != null) { properties.ContentMD5 = response.Headers[Constants.HeaderConstants.FileContentMD5Header]; } else { properties.ContentMD5 = response.Headers[HttpResponseHeader.ContentMd5]; } properties.ContentType = response.Headers[HttpResponseHeader.ContentType]; properties.CacheControl = response.Headers[HttpResponseHeader.CacheControl]; string fileEncryption = response.Headers[Constants.HeaderConstants.ServerEncrypted]; properties.IsServerEncrypted = string.Equals(fileEncryption, Constants.HeaderConstants.TrueHeader, StringComparison.OrdinalIgnoreCase); // Get the content length. Prioritize range and x-ms over content length for the special cases. string rangeHeader = response.Headers[HttpResponseHeader.ContentRange]; string contentLengthHeader = response.Headers[Constants.HeaderConstants.ContentLengthHeader]; string fileContentLengthHeader = response.Headers[Constants.HeaderConstants.FileContentLengthHeader]; if (!string.IsNullOrEmpty(rangeHeader)) { properties.Length = long.Parse(rangeHeader.Split('/')[1], CultureInfo.InvariantCulture); } else if (!string.IsNullOrEmpty(fileContentLengthHeader)) { properties.Length = long.Parse(fileContentLengthHeader, CultureInfo.InvariantCulture); } else if (!string.IsNullOrEmpty(contentLengthHeader)) { // On Windows Phone, ContentLength property is not always same as Content-Length header, // so we try to parse the header first. properties.Length = long.Parse(contentLengthHeader, CultureInfo.InvariantCulture); } else { properties.Length = response.ContentLength; } return(properties); }
public FileProperties GetLogsHeadFileProperties() { // Use a temporary FileProperties in case another thread sets this.logsHeadFileProperties before this // method returns FileProperties properties = this.logsHeadFileProperties; if (properties == null) { try { properties = this.context.FileSystem.GetFileProperties(this.logsHeadPath); this.logsHeadFileProperties = properties; } catch (Exception e) { EventMetadata metadata = this.CreateEventMetadata(relativePath: null, exception: e); this.context.Tracer.RelatedWarning(metadata, "GetLogsHeadFileProperties: Exception thrown from GetFileProperties", Keywords.Telemetry); properties = FileProperties.DefaultFile; // Leave logsHeadFileProperties null to indicate that it is still needs to be refreshed this.logsHeadFileProperties = null; } } return(properties); }
/* Private methods */ private FileProperties GetUpdatedFileProperties(FileProperties properties) { SubtitleFormat format = BuiltInSubtitleFormats.GetFormat(properties.SubtitleType); TimingMode newTimingMode = (format.Mode == SubtitleMode.Both) ? properties.TimingMode : format.ModeAsTimingMode; return(new FileProperties(properties.Path, properties.Encoding, properties.SubtitleType, newTimingMode, properties.NewlineType)); }
private static void Main() { string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); DirectoryInfo dirInfo = new DirectoryInfo(myDocuments); FileInfo[] filesInfo = dirInfo.GetFiles(); foreach (FileInfo fInfo in filesInfo) { FileProperties fProp = new FileProperties { name = fInfo.Name, extension = fInfo.Extension, length = fInfo.Length/1024.0 }; listFileProp.Add(fProp); } var queryFiles = from fProp in listFileProp orderby fProp.length group fProp by fProp.extension into extensionGroup orderby extensionGroup.Count() descending, extensionGroup.Key select extensionGroup; string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); StreamWriter sw = new StreamWriter(desktop + "/report.txt"); foreach (var extGroup in queryFiles) { sw.WriteLine(extGroup.Key); foreach (var fProp in extGroup) sw.WriteLine("--{0} - {1:f2}kb", fProp.name, fProp.length); } sw.Close(); }
/// <summary> /// 设置文件名 /// </summary> /// <param name="info"></param> protected virtual void SetFileProperty(TEntityType info) { if (FileProperties == null || FileProperties.Count == 0 || FileRepository == null) { return; } var rev = FileProperties.Aggregate(false, (current, fileProperty) => current || info.HasSaveProperty(fileProperty.FilePropertyName)); if (!rev) { return; } var server = Winner.Creator.Get <Winner.Base.IProperty>(); var fileroute = Winner.Creator.Get <Winner.Storage.IFile>(); foreach (var fileProperty in FileProperties) { if (!info.HasSaveProperty(fileProperty.FilePropertyName)) { continue; } var fileName = server.GetValue <string>(info, fileProperty.FilePropertyName); if (string.IsNullOrEmpty(fileName)) { continue; } var fileByte = server.GetValue <byte[]>(info, fileProperty.BytePropertyName); if (fileByte == null || fileByte.Length == 0) { continue; } string setValue; if (info.SaveType == SaveType.Add) { setValue = fileroute.CreateFileName(fileName); } else { var dataEntity = Repository.Get <TEntityType>(info.Id); setValue = server.GetValue <string>(dataEntity, fileProperty.FilePropertyName); if (dataEntity == null || string.IsNullOrEmpty(setValue)) { setValue = fileroute.CreateFileName(fileName); } else { var exetion = System.IO.Path.GetExtension(setValue); if (!string.IsNullOrEmpty(exetion)) { setValue = setValue.Replace(exetion, System.IO.Path.GetExtension(fileName)); } } } setValue = setValue ?? ""; server.SetValue(info, fileProperty.FilePropertyName, setValue); } }
/// <summary> /// Gets the file's properties from the response. /// </summary> /// <param name="response">The web response.</param> /// <returns>The file's properties.</returns> public static FileProperties GetProperties(HttpResponseMessage response) { FileProperties properties = new FileProperties(); if (response.Content != null) { properties.LastModified = response.Content.Headers.LastModified; properties.ContentEncoding = HttpWebUtility.CombineHttpHeaderValues(response.Content.Headers.ContentEncoding); properties.ContentLanguage = HttpWebUtility.CombineHttpHeaderValues(response.Content.Headers.ContentLanguage); if (response.Content.Headers.ContentDisposition != null) { properties.ContentDisposition = response.Content.Headers.ContentDisposition.ToString(); } if (response.Content.Headers.ContentMD5 != null && response.Content.Headers.ContentRange == null) { properties.ContentMD5 = Convert.ToBase64String(response.Content.Headers.ContentMD5); } else if (!string.IsNullOrEmpty(response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.FileContentMD5Header))) { properties.ContentMD5 = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.FileContentMD5Header); } if (response.Content.Headers.ContentType != null) { properties.ContentType = response.Content.Headers.ContentType.ToString(); } // Get the content length. Prioritize range and x-ms over content length for the special cases. string contentLengthHeader = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.FileContentLengthHeader); if ((response.Content.Headers.ContentRange != null) && response.Content.Headers.ContentRange.HasLength) { properties.Length = response.Content.Headers.ContentRange.Length.Value; } else if (!string.IsNullOrEmpty(contentLengthHeader)) { properties.Length = long.Parse(contentLengthHeader); } else if (response.Content.Headers.ContentLength.HasValue) { properties.Length = response.Content.Headers.ContentLength.Value; } } if (response.Headers.CacheControl != null) { properties.CacheControl = response.Headers.CacheControl.ToString(); } if (response.Headers.ETag != null) { properties.ETag = response.Headers.ETag.ToString(); } return(properties); }
public OutputFile() { FileProperties = new FileProperties { CustomTool = string.Empty, BuildAction = BuildAction.None }; }
void AddFormatProperties(GDATFile file) { string formattedMagic = FileProperties.GetExtension(file.Magic); FileProperties props = new FileProperties("Format", formattedMagic); Properties.Add(props); AddFormatDefinition(formattedMagic); }
void AddSizeProperty(GDATFile file) { FileProperties props = new FileProperties(); props.Property = "Size"; props.Value = GetSize(file); Properties.Add(props); }
private async void Initialize(string filePath) { Workspace.Instance.SetStatus(TaskStatusType.Loading, $"Loading a file... ({filePath})"); // Set status. // Load file. string loadedFilePath = await FileLoadAsync(filePath); try { if (loadedFilePath == null) { OnClose(); return; } else { // Initialize AudioPlayback and Visualizations. _visualizations = ReflectionHelper.CreateAllInstancesOf <IVisualizationPlugin>().ToList(); _selectedVisualization = _visualizations.FirstOrDefault(); _audioPlayback = new AudioPlayback(); _audioPlayback.MaximumCalculated += OnAudioGraphMaximumCalculated; _audioPlayback.FftCalculated += OnAudioGraphFftCalculated; string extension = Path.GetExtension(filePath).ToLower(); if (extension == ".ogg" || extension == ".rpgmvo" || extension == ".ogg_") { _audioPlayback.Load(loadedFilePath, true); // Load audio file using Ogg Vorbis wave reader. } else { _audioPlayback.Load(loadedFilePath); } // Initialize track bar. _trackBarTimer = new Timer(); _trackBarTimer.Interval = 500; _trackBarTimer.Elapsed += new ElapsedEventHandler(OnTrackBarTimerElapsed); _trackBarMaximumValue = _audioPlayback.GetTotalTime(); TimeSpan current = TimeSpan.Zero; _trackBarString = $"{current.ToString(@"hh\:mm\:ss")} / {_trackBarMaximumValue.ToString(@"hh\:mm\:ss")}"; // Load file properties. _fileProperties = new FileProperties(filePath); } } catch (Exception ex) { Workspace.Instance.Report.AddReportWithIdentifier($"{ex.Message}\r\n{ex.StackTrace}", ReportType.Warning); } finally { Workspace.Instance.SetStatus(TaskStatusType.Completed, $"Completed."); // Set status. } }
internal static void ShowFileProperties(Form form, String fileName, bool sessionFile = false) { FileProperties filePropertiesWindow = new FileProperties { Owner = form }; filePropertiesWindow.InitializeForm(fileName, sessionFile); filePropertiesWindow.ShowDialog(form); }
public static void FindFiles(object objFileProperties, out SqlString fileName, out SqlInt64 fileSize, out SqlDateTime creationTime) { //I'm using here the FileProperties class defined above FileProperties fileProperties = (FileProperties)objFileProperties; fileName = fileProperties.FileName; fileSize = fileProperties.FileSize; creationTime = fileProperties.CreationTime; }
public static void GetOneFile(object objFileProperties, out SqlString fileName, out SqlInt64 fileSize, out SqlDateTime creationTime) { FileProperties fileProperties = (FileProperties)objFileProperties; fileName = fileProperties.FileName; fileSize = fileProperties.FileSize; creationTime = fileProperties.CreationTime; }
private void ClearTranslationStatus() { this.isTranslationLoaded = false; this.wasTranslationModified = false; this.translationFile = null; this.canTranslationBeSaved = false; ClearTranslationModified(); }
public FilePropertiesTest() { var name = "file"; var lastWriteTime = DateTime.Now; var length = 1234; m_Instance1 = new FileProperties() { Name = name, LastWriteTime = lastWriteTime, Length = length }; m_Instance2 = new FileProperties() { Name = name, LastWriteTime = lastWriteTime, Length = length }; m_Instance3 = new FileProperties() { Name = name.ToUpper(), LastWriteTime = lastWriteTime, Length = length }; }
/// <summary> /// Gets the file's properties from the response. /// </summary> /// <param name="response">The web response.</param> /// <returns>The file's properties.</returns> public static FileProperties GetProperties(HttpResponseMessage response) { FileProperties properties = new FileProperties(); if (response.Content != null) { properties.LastModified = response.Content.Headers.LastModified; properties.ContentEncoding = HttpWebUtility.CombineHttpHeaderValues(response.Content.Headers.ContentEncoding); properties.ContentLanguage = HttpWebUtility.CombineHttpHeaderValues(response.Content.Headers.ContentLanguage); if (response.Content.Headers.ContentDisposition != null) { properties.ContentDisposition = response.Content.Headers.ContentDisposition.ToString(); } if (response.Content.Headers.ContentMD5 != null) { properties.ContentMD5 = Convert.ToBase64String(response.Content.Headers.ContentMD5); } if (response.Content.Headers.ContentType != null) { properties.ContentType = response.Content.Headers.ContentType.ToString(); } // Get the content length. Prioritize range and x-ms over content length for the special cases. string contentLengthHeader = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.FileContentLengthHeader); if ((response.Content.Headers.ContentRange != null) && response.Content.Headers.ContentRange.HasLength) { properties.Length = response.Content.Headers.ContentRange.Length.Value; } else if (!string.IsNullOrEmpty(contentLengthHeader)) { properties.Length = long.Parse(contentLengthHeader); } else if (response.Content.Headers.ContentLength.HasValue) { properties.Length = response.Content.Headers.ContentLength.Value; } } if (response.Headers.CacheControl != null) { properties.CacheControl = response.Headers.CacheControl.ToString(); } if (response.Headers.ETag != null) { properties.ETag = response.Headers.ETag.ToString(); } return properties; }
/// <summary> /// Gets the file's properties from the response. /// </summary> /// <param name="response">The web response.</param> /// <returns>The file's properties.</returns> public static FileProperties GetProperties(HttpWebResponse response) { CommonUtility.AssertNotNull("response", response); FileProperties properties = new FileProperties(); properties.ETag = HttpResponseParsers.GetETag(response); #if WINDOWS_PHONE properties.LastModified = HttpResponseParsers.GetLastModified(response); properties.ContentLanguage = response.Headers[Constants.HeaderConstants.ContentLanguageHeader]; #else properties.LastModified = response.LastModified.ToUniversalTime(); properties.ContentLanguage = response.Headers[HttpResponseHeader.ContentLanguage]; #endif properties.ContentDisposition = response.Headers[Constants.HeaderConstants.ContentDispositionResponseHeader]; properties.ContentEncoding = response.Headers[HttpResponseHeader.ContentEncoding]; properties.ContentMD5 = response.Headers[HttpResponseHeader.ContentMd5]; properties.ContentType = response.Headers[HttpResponseHeader.ContentType]; properties.CacheControl = response.Headers[HttpResponseHeader.CacheControl]; // Get the content length. Prioritize range and x-ms over content length for the special cases. string rangeHeader = response.Headers[HttpResponseHeader.ContentRange]; string contentLengthHeader = response.Headers[Constants.HeaderConstants.ContentLengthHeader]; string fileContentLengthHeader = response.Headers[Constants.HeaderConstants.FileContentLengthHeader]; if (!string.IsNullOrEmpty(rangeHeader)) { properties.Length = long.Parse(rangeHeader.Split('/')[1], CultureInfo.InvariantCulture); } else if (!string.IsNullOrEmpty(fileContentLengthHeader)) { properties.Length = long.Parse(fileContentLengthHeader, CultureInfo.InvariantCulture); } else if (!string.IsNullOrEmpty(contentLengthHeader)) { // On Windows Phone, ContentLength property is not always same as Content-Length header, // so we try to parse the header first. properties.Length = long.Parse(contentLengthHeader, CultureInfo.InvariantCulture); } else { properties.Length = response.ContentLength; } return properties; }
/// <summary> /// Constructs a web request to create a new file. /// </summary> /// <param name="uri">The absolute URI to the file.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="properties">The properties to set for the file.</param> /// <param name="fileSize">The size of the file.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <param name="useVersionHeader">A boolean value indicating whether to set the <i>x-ms-version</i> HTTP header.</param> /// <param name="operationContext">An <see cref="OperationContext" /> object for tracking the current operation.</param> /// <returns>A <see cref="System.Net.HttpWebRequest"/> object.</returns> public static HttpWebRequest Create(Uri uri, int? timeout, FileProperties properties, long fileSize, AccessCondition accessCondition, bool useVersionHeader, OperationContext operationContext) { CommonUtility.AssertNotNull("properties", properties); HttpWebRequest request = HttpWebRequestFactory.CreateWebRequest(WebRequestMethods.Http.Put, uri, timeout, null /* builder */, useVersionHeader, operationContext); if (properties.CacheControl != null) { request.Headers[HttpRequestHeader.CacheControl] = properties.CacheControl; } if (properties.ContentType != null) { // Setting it using Headers is an exception request.ContentType = properties.ContentType; } if (properties.ContentMD5 != null) { request.Headers[HttpRequestHeader.ContentMd5] = properties.ContentMD5; } if (properties.ContentLanguage != null) { request.Headers[HttpRequestHeader.ContentLanguage] = properties.ContentLanguage; } if (properties.ContentEncoding != null) { request.Headers[HttpRequestHeader.ContentEncoding] = properties.ContentEncoding; } if (properties.ContentDisposition != null) { request.Headers[Constants.HeaderConstants.FileContentDispositionRequestHeader] = properties.ContentDisposition; } request.Headers[Constants.HeaderConstants.FileType] = Constants.HeaderConstants.File; request.Headers[Constants.HeaderConstants.FileContentLengthHeader] = fileSize.ToString(NumberFormatInfo.InvariantInfo); properties.Length = fileSize; request.ApplyAccessCondition(accessCondition); return request; }
public static void LoadFiles(string systemFolder, string folder, string systemName, List<FileProperties> curFiles) { if (!Directory.Exists(folder)) return; var md5 = MD5.Create(); foreach (var fileName in Directory.GetFiles(folder)) { var fileInfo = new FileInfo(fileName); var fileProperties = new FileProperties { // ReSharper disable PossibleNullReferenceException Name = Path.GetFileName(fileName).ToLower(), // ReSharper restore PossibleNullReferenceException Path = folder.StartsWith(systemFolder) ? folder.Substring(systemFolder.Length).ToLower() : folder, TargetSystemString = systemName, TimeUpdated = fileInfo.LastWriteTime, Length = fileInfo.Length, }; var systemNameTyped = SystemNameParser.ParseSystemName(systemName); if (systemNameTyped.HasValue) fileProperties.TargetSystem = systemNameTyped.Value; try { using (var stream = File.OpenRead(fileName)) { var hash = md5.ComputeHash(stream); var sb = new StringBuilder(); for (var i = 0; i < hash.Length; i++) sb.Append(hash[i].ToString("x2")); fileProperties.HashCode = sb.ToString(); } curFiles.Add(fileProperties); } catch { // различные ошибки чтения файла } } // зайти внутрь foreach (var dir in Directory.GetDirectories(folder)) { LoadFiles(systemFolder, dir, systemName, curFiles); } }
/// <summary> /// Constructs a web request to create a new file. /// </summary> /// <param name="uri">The absolute URI to the file.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="properties">The properties to set for the file.</param> /// <param name="fileSize">For a file, the size of the file. This parameter is ignored /// for block files.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage Create(Uri uri, int? timeout, FileProperties properties, long fileSize, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, null /* builder */, content, operationContext, canonicalizer, credentials); if (properties.CacheControl != null) { request.Headers.CacheControl = CacheControlHeaderValue.Parse(properties.CacheControl); } if (content != null) { if (properties.ContentType != null) { content.Headers.ContentType = MediaTypeHeaderValue.Parse(properties.ContentType); } if (properties.ContentMD5 != null) { content.Headers.ContentMD5 = Convert.FromBase64String(properties.ContentMD5); } if (properties.ContentLanguage != null) { content.Headers.ContentLanguage.Add(properties.ContentLanguage); } if (properties.ContentEncoding != null) { content.Headers.ContentEncoding.Add(properties.ContentEncoding); } if (properties.ContentDisposition != null) { content.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse(properties.ContentDisposition); } } request.Headers.Add(Constants.HeaderConstants.FileType, Constants.HeaderConstants.File); request.Headers.Add(Constants.HeaderConstants.FileContentLengthHeader, fileSize.ToString(NumberFormatInfo.InvariantInfo)); properties.Length = fileSize; request.ApplyAccessCondition(accessCondition); return request; }
static void Main() { //get the content of "My Documents" folder string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); DirectoryInfo dirInfo = new DirectoryInfo(myDocuments); FileInfo[] filesInfo = dirInfo.GetFiles(); //init class instances and add them to list: foreach (FileInfo fInfo in filesInfo) { FileProperties fProp = new FileProperties { name = fInfo.Name, extension = fInfo.Extension, length = fInfo.Length / 1024.0 }; listFileProp.Add(fProp); } //query files var queryFiles = from fProp in listFileProp orderby fProp.length group fProp by fProp.extension into extensionGroup orderby extensionGroup.Count() descending, extensionGroup.Key select extensionGroup; //write the result string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); StreamWriter sw = new StreamWriter(desktop + "/report.txt"); foreach (var extGroup in queryFiles) { sw.WriteLine(extGroup.Key); foreach (var fProp in extGroup) sw.WriteLine("--{0} - {1:f2}kb", fProp.name, fProp.length); } sw.Close(); //Check our your desktop for report.txt }
public static HttpWebRequest PutFileRequest(FileContext context, string shareName, string fileName, FileProperties properties, byte[] content, long fileSize, AccessCondition accessCondition) { bool valid = FileTests.ShareNameValidator(shareName) && FileTests.FileNameValidator(fileName) && FileTestUtils.ContentValidator(content); Uri uri = FileTests.ConstructPutUri(context.Address, shareName, fileName); HttpWebRequest request = null; OperationContext opContext = new OperationContext(); try { request = FileHttpWebRequestFactory.Create(uri, context.Timeout, properties, fileSize, accessCondition, true, opContext); } catch (InvalidOperationException) { if (valid) { Assert.Fail(); } } if (valid) { Assert.IsNotNull(request); Assert.IsNotNull(request.Method); Assert.AreEqual("PUT", request.Method); FileTestUtils.VersionHeader(request, false); FileTestUtils.ContentTypeHeader(request, null); FileTestUtils.ContentDispositionHeader(request, properties.ContentDisposition); FileTestUtils.ContentEncodingHeader(request, properties.ContentEncoding); FileTestUtils.ContentLanguageHeader(request, null); FileTestUtils.CacheControlHeader(request, null); FileTestUtils.FileTypeHeader(request, "File"); FileTestUtils.FileSizeHeader(request, properties.Length); } return request; }
void CopyNoMetaDataFiles(FileProperties file) { string targetYear = TargetFolder + "\\" + DateTime.Now.Year; string month = DateTime.Now.ToString("MMMM").UppercaseFirst(); string monthNumber = DateTime.Now.Month.ToString(CultureInfo.InvariantCulture); string targetMonth = targetYear + "\\" + monthNumber + ". " + month; targetMonth.Substring(0, 1).ToUpper(); string whatEver = targetMonth + "\\" + NoDataFolder; //Om ÅR inte finns if (!Directory.Exists(targetYear)) { Directory.CreateDirectory(targetYear); } //om MÅNAD inte finns if (!Directory.Exists(targetMonth)) { Directory.CreateDirectory(targetMonth); } //om WHATEVA-mappen inte finns if (!Directory.Exists(whatEver)) { Directory.CreateDirectory(whatEver); } file.FileName = Path.GetFileName(file.FileName); if (file.FileName != null) whatEver = Path.Combine(whatEver, file.FileName); File.Copy(file.FullImagePath, whatEver, true); }
void CopyFiles(FileProperties file) { var targetYear = TargetFolder + "\\" + file.DateTaken.Year; var month = file.DateTaken.ToString("MMMM").UppercaseFirst(); var monthNumber = file.DateTaken.Month.ToString(CultureInfo.InvariantCulture); var targetMonth = targetYear + "\\" + monthNumber + ". " + month; //Om ÅR inte finns if (!Directory.Exists(targetYear)) { Directory.CreateDirectory(targetYear); } //om MÅNAD inte finns if (!Directory.Exists(targetMonth)) { Directory.CreateDirectory(targetMonth); } var filesThisDay = _theImages.Count(i => i.DateTaken.Year == file.DateTaken.Year && i.DateTaken.Month == file.DateTaken.Month && i.DateTaken.Day == file.DateTaken.Day); if (filesThisDay > 20) { string targetDay; //For images taken on late nights ex. on a party. Copies the image to the same day as the party started. if (file.DateTaken.Hour < 4 && file.DateTaken.Day != 1) { var lateNight = file.DateTaken.Day - 1; targetDay = targetMonth + "\\" + lateNight; } else { targetDay = targetMonth + "\\" + file.DateTaken.Day; } //om DAG inte finns, skapa mappen if (!Directory.Exists(targetDay)) { Directory.CreateDirectory(targetDay); } file.FileName = Path.GetFileName(file.FullImagePath); if (file.FileName != null) targetDay = Path.Combine(targetDay, file.FileName); File.Copy(file.FullImagePath, targetDay, true); } else { file.FileName = Path.GetFileName(file.FullImagePath); if (file.FileName != null) targetMonth = Path.Combine(targetMonth, file.FileName); File.Copy(file.FullImagePath, targetMonth, true); } }
public static void GetFileResponse(HttpWebResponse response, FileContext context, FileProperties properties, HttpStatusCode? expectedError) { Assert.IsNotNull(response); if (expectedError == null) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); FileTestUtils.LastModifiedHeader(response); FileTestUtils.ETagHeader(response); FileTestUtils.RequestIdHeader(response); } else { Assert.AreEqual(expectedError, response.StatusCode, response.StatusDescription); } response.Close(); }
private FileProperties GetFileProperties(string path) { var fileProperties = new FileProperties(); if (string.IsNullOrEmpty(path)) { return fileProperties; } fileProperties.Path = path; fileProperties.Exists = fileSystem.FileExists(path); fileProperties.LastModifiedDate = fileSystem.GetLastWriteTime(path); return fileProperties; }
/// <summary> /// Constructs a web request to set system properties for a file. /// </summary> /// <param name="uri">The absolute URI to the file.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="properties">The file's properties.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <param name="useVersionHeader">A boolean value indicating whether to set the <i>x-ms-version</i> HTTP header.</param> /// <param name="operationContext">An <see cref="OperationContext" /> object for tracking the current operation.</param> /// <returns>A <see cref="System.Net.HttpWebRequest"/> object.</returns> public static HttpWebRequest SetProperties(Uri uri, int? timeout, FileProperties properties, AccessCondition accessCondition, bool useVersionHeader, OperationContext operationContext) { CommonUtility.AssertNotNull("properties", properties); UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "properties"); HttpWebRequest request = HttpWebRequestFactory.CreateWebRequest(WebRequestMethods.Http.Put, uri, timeout, builder, useVersionHeader, operationContext); if (properties != null) { request.AddOptionalHeader(Constants.HeaderConstants.FileCacheControlHeader, properties.CacheControl); request.AddOptionalHeader(Constants.HeaderConstants.FileContentEncodingHeader, properties.ContentEncoding); request.AddOptionalHeader(Constants.HeaderConstants.FileContentDispositionRequestHeader, properties.ContentDisposition); request.AddOptionalHeader(Constants.HeaderConstants.FileContentLanguageHeader, properties.ContentLanguage); request.AddOptionalHeader(Constants.HeaderConstants.FileContentMD5Header, properties.ContentMD5); request.AddOptionalHeader(Constants.HeaderConstants.FileContentTypeHeader, properties.ContentType); } request.ApplyAccessCondition(accessCondition); return request; }
public void CreateImageObject(string img, string filename) { _fp = new FileProperties(); _fs = new FileStream(img, FileMode.Open); _decoder = BitmapDecoder.Create(_fs, BitmapCreateOptions.None, BitmapCacheOption.Default); _frame = _decoder.Frames[0]; _metadata = _frame.Metadata as BitmapMetadata; if (_metadata != null && _metadata.DateTaken != null) { _fp.DateTaken = DateTime.Parse(_metadata.DateTaken); _fp.FullImagePath = img; } else { _fp.FullImagePath = img; } _fp.FileName = filename; _fp.FolderPath = Path.GetDirectoryName(img); _theImages.Add(_fp); _fs.Close(); }
public Ba(FileProperties properties, Headers.Abstract.LocatorFileHeader header, RlViewer.Navigation.NavigationContainer navi) : base(properties, header, navi) { _header = header as Headers.Concrete.Ba.BaHeader; _navi = navi; }
private void TestFilePropertiesNoneClone(FileProperties fp) { // Do not set any members and clone FileProperties fpClone = fp.Clone() as FileProperties; // Set values in source object fp.ContentType = "foo_11"; fp.ContentEncoding = "foo_12"; fp.Headers = new Dictionary<string, object>(); fp.Headers.Add("foo_13", "foo_14"); fp.Headers.Add("foo_15", "foo_16"); fp.Priority = 34; fp.ReplyTo = "foo_17"; fp.MessageId = "foo_18"; fp.Filename = "foo_19"; fp.Timestamp = new AmqpTimestamp(234); fp.ClusterId = "foo_20"; // Check that no member is present in clone Assert.AreEqual(false, fpClone.IsContentTypePresent()); Assert.AreEqual(false, fpClone.IsContentEncodingPresent()); Assert.AreEqual(false, fpClone.IsHeadersPresent()); Assert.AreEqual(false, fpClone.IsPriorityPresent()); Assert.AreEqual(false, fpClone.IsReplyToPresent()); Assert.AreEqual(false, fpClone.IsMessageIdPresent()); Assert.AreEqual(false, fpClone.IsFilenamePresent()); Assert.AreEqual(false, fpClone.IsTimestampPresent()); Assert.AreEqual(false, fpClone.IsClusterIdPresent()); }
public static FileInformation GetInformation(string basePath, string path, FileProperties requiredProperties) { FileInformation info = GetInformation(File.OpenRead($"{basePath}/{path}"), requiredProperties); if (requiredProperties.HasFlag(FileProperties.Path)) { info.Path = path.Replace(System.IO.Path.DirectorySeparatorChar, '/'); } return info; }
/// <summary> /// Method generates patch /// </summary> public List<string> GeneratePatch(FileProperties firstFileInfo, FileProperties secondFileInfo) { /// Creates file with changes (final version of patch) return CreatePatch(_firstFile, _secondFile, DiffText(_firstFile, _secondFile, false), firstFileInfo, secondFileInfo); }
/// <summary> /// Constructs a web request to set system properties for a file. /// </summary> /// <param name="uri">The absolute URI to the file.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="properties">The file's properties.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage SetProperties(Uri uri, int? timeout, FileProperties properties, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "properties"); StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials); if (properties != null) { request.AddOptionalHeader(Constants.HeaderConstants.FileCacheControlHeader, properties.CacheControl); request.AddOptionalHeader(Constants.HeaderConstants.FileContentDispositionRequestHeader, properties.ContentDisposition); request.AddOptionalHeader(Constants.HeaderConstants.FileContentEncodingHeader, properties.ContentEncoding); request.AddOptionalHeader(Constants.HeaderConstants.FileContentLanguageHeader, properties.ContentLanguage); request.AddOptionalHeader(Constants.HeaderConstants.FileContentMD5Header, properties.ContentMD5); request.AddOptionalHeader(Constants.HeaderConstants.FileContentTypeHeader, properties.ContentType); } request.ApplyAccessCondition(accessCondition); return request; }
private void CreateFileObject(string file) { _fp = new FileProperties(); _fi = new FileInfo(file); _fp.DateTaken = _fi.LastWriteTime; _fp.FullImagePath = _fi.FullName; _fp.FileName = _fi.Name; _fp.FolderPath = _fi.DirectoryName; _fp.FileType = FileProperties.FileTypes.Video; _theImages.Add(_fp); }
void CreateProblemFileObject(string file) { if (!file.EndsWith("db") && !file.EndsWith("desktop.ini")) { _fp = new FileProperties(); _fi = new FileInfo(file); _fp.FileName = _fi.FullName; _failedFiles.Add(_fp); ShowFailedFiles.Visibility = Visibility.Visible; } }
public FileInformation AddProperties(Stream stream, FileProperties requiredProperties) { requiredProperties -= requiredProperties & GetProperties(); if (Size == null && (requiredProperties.HasFlag(FileProperties.Size) || requiredProperties.HasFlag(FileProperties.BlockSize) || (requiredProperties & FileProperties.AllBlockHashes) != FileProperties.None || (requiredProperties & FileProperties.AllHashes) != FileProperties.None)) { Size = stream.Length; } if (BlockSize == null && (requiredProperties & (FileProperties.BlockSize | FileProperties.AllHashes | FileProperties.AllBlockHashes)) != FileProperties.None) { BlockSize = GetBlockSize(Size.Value); } int readLength = 0; byte[] buffer = new byte[BlockSize == null ? SliceLength : BlockSize.Value]; if (stream != null && stream.CanSeek) { // Assume at head if stream is not seekable. stream.Seek(0, SeekOrigin.Begin); } if (requiredProperties.HasFlag(FileProperties.SliceMD5)) { readLength = stream.Read(buffer, 0, SliceLength); SliceMD5 = (readLength == SliceLength) ? new MD5CryptoServiceProvider().ComputeHash(buffer, 0, SliceLength).ToHexString() : null; } if ((requiredProperties & FileProperties.AllHashes) != FileProperties.None) { List<HashAlgorithm> hashers = new List<HashAlgorithm> { requiredProperties.HasFlag(FileProperties.MD5) ? new MD5CryptoServiceProvider() : null, requiredProperties.HasFlag(FileProperties.SHA1) ? new SHA1CryptoServiceProvider() : null, requiredProperties.HasFlag(FileProperties.SHA256) ? new SHA256CryptoServiceProvider() : null }; BlockMD5 = requiredProperties.HasFlag(FileProperties.BlockMD5) ? new List<string>() : BlockMD5; BlockSHA1 = requiredProperties.HasFlag(FileProperties.BlockSHA1) ? new List<string>() : BlockSHA1; BlockSHA256 = requiredProperties.HasFlag(FileProperties.BlockSHA256) ? new List<string>() : BlockSHA256; List<HashAlgorithm> blockHashers = new List<HashAlgorithm> { requiredProperties.HasFlag(FileProperties.BlockMD5) ? new MD5CryptoServiceProvider() : null, requiredProperties.HasFlag(FileProperties.BlockSHA1) ? new SHA1CryptoServiceProvider() : null, requiredProperties.HasFlag(FileProperties.BlockSHA256) ? new SHA256CryptoServiceProvider() : null }; List<IHash> additionalHashers = new List<IHash> { requiredProperties.HasFlag(FileProperties.CRC32) ? HashFactory.Checksum.CreateCRC32a() : null, requiredProperties.HasFlag(FileProperties.Adler32) ? HashFactory.Checksum.CreateAdler32() : null }; foreach (var hasher in additionalHashers) { hasher?.Initialize(); } while ((readLength += stream.Read(buffer, readLength, BlockSize.Value - readLength)) != 0) { Parallel.ForEach( hashers, hasher => { hasher?.TransformBlock(buffer, 0, readLength, buffer, 0); } ); Parallel.ForEach( additionalHashers, hasher => { hasher?.TransformBytes(buffer, 0, readLength); } ); if (requiredProperties.HasFlag(FileProperties.BlockMD5)) { BlockMD5.Add(blockHashers[0].ComputeHash(buffer, 0, readLength).ToHexString()); } if (requiredProperties.HasFlag(FileProperties.BlockSHA1)) { BlockSHA1.Add(blockHashers[1].ComputeHash(buffer, 0, readLength).ToHexString()); } if (requiredProperties.HasFlag(FileProperties.BlockSHA256)) { BlockSHA256.Add(blockHashers[2].ComputeHash(buffer, 0, readLength).ToHexString()); } readLength = 0; } foreach (var hasher in hashers) { hasher?.TransformFinalBlock(buffer, 0, 0); } MD5 = MD5 ?? hashers[0]?.Hash.ToHexString(); SHA1 = SHA1 ?? hashers[1]?.Hash.ToHexString(); SHA256 = SHA256 ?? hashers[2]?.Hash.ToHexString(); CRC32 = CRC32 ?? additionalHashers[0]?.TransformFinal().GetBytes().Reverse().ToArray().ToHexString(); Adler32 = Adler32 ?? additionalHashers[1]?.TransformFinal().GetBytes().Reverse().ToArray().ToHexString(); } if (requiredProperties.HasFlag(FileProperties.EncryptionKey)) { EncryptionKey = GenerateEncryptionKey(); } return this; }
public void GetHashCode_returns_the_same_value_is_name_is_equal() { var file1 = new FileProperties() {Name = "file", LastWriteTime = DateTime.Now, Length = 1234}; var file2 = new FileProperties() { Name = "fILe", LastWriteTime = DateTime.MinValue, Length = 5678 }; Assert.Equal(file1.GetHashCode(), file2.GetHashCode()); }
public void FetchDetails() { var props = new FileProperties(); props.ShellObject = ShellObject.FromParsingName(FullPath); props.Length = (long)(props.ShellObject.Properties.System.Size.Value ?? 0); props.Created = props.ShellObject.Properties.System.DateCreated.Value; props.LastModified = props.ShellObject.Properties.System.DateCreated.Value; props.ShellObject.Thumbnail.FormatOption = ShellThumbnailFormatOption.IconOnly; props.ShellObject.Thumbnail.RetrievalOption = ShellThumbnailRetrievalOption.Default; props.Thumbnail = props.ShellObject.Thumbnail.SmallBitmapSource; //props.Thumbnail.Freeze(); Properties = props; }
/// <summary> /// Method creates patch from files difference objects /// </summary> /// <param name="differences"></param> /// <returns></returns> private List<string> CreatePatch(List<string> firstFile, List<string> secondFile, List<Difference> differences, FileProperties firstFileInfo, FileProperties secondFileInfo) { List<string> patch = new List<string>(); List<string> diffRange = new List<string>(); string lastAction = string.Empty; int linesLevel = 0; int firstRange = 0; int secondRange = 0; int firstIndex = 0; int secondIndex = 0; int deletedIndex, insertedIndex; // if there are diffs beetwen files we create patch if (differences.Count != 0) { patch.Add("--- " + firstFileInfo.FilePath + " " + DateTime.Now.ToString()); patch.Add("+++ " + secondFileInfo.FilePath + " " + DateTime.Now.ToString()); // Iterate every diff object and update first file for (int x = 0; x < differences.Count; ++x) { // diffrence between deleted and inserted lines // result give us 3 possible operations int res = differences[x].deletedAmount - differences[x].insertedAmount; // set indexes to patch file deletedIndex = firstIndex + 1; insertedIndex = secondIndex + 1; // 1. if deleted and inserted are equal if (res.Equals(0)) { // complete start lines for (int i = firstIndex; i < differences[x].deletedIndex; ++i) { diffRange.Add(firstFile[i]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } // Insert changed lines with modyfied style for (int i = 0; i < differences[x].deletedAmount; ++i) { diffRange.Add("-" + firstFile[firstIndex]); diffRange.Add("+" + secondFile[secondIndex]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } // complete lines to next diff // there is more than 1 diff if (x + 1 < differences.Count) { int size; if (lastAction.Equals("d")) { size = Math.Min(differences[x + 1].deletedIndex, differences[x + 1].insertedIndex - linesLevel); for (int i = firstIndex; i < size; ++i) { diffRange.Add(firstFile[i]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } } else { size = Math.Min(differences[x + 1].deletedIndex - linesLevel, differences[x + 1].insertedIndex); for (int i = secondIndex; i < size; ++i) { diffRange.Add(secondFile[i]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } } } // we are at last diff else { for (int i = firstIndex; i < firstFile.Count; ++i) { diffRange.Add(firstFile[i]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } } } // 2. if deleted < inserted if (res < 0) { if (lastAction.Equals("d")) { linesLevel *= -1; } // complete start lines to first file for (int i = firstIndex; i < differences[x].insertedIndex + linesLevel; ++i) { diffRange.Add(firstFile[i]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } // if there is some changed lines if (differences[x].deletedAmount > 0) { // we add changed lines to first file for (int i = 0; i < differences[x].deletedAmount; ++i) { diffRange.Add("-" + firstFile[firstIndex]); diffRange.Add("+" + secondFile[secondIndex]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } } // add inserted lines for (int i = 0; i < differences[x].insertedAmount - differences[x].deletedAmount; ++i) { diffRange.Add("+" + secondFile[secondIndex]); ++secondIndex; ++secondRange; } /// set actual line lvl linesLevel += res; lastAction = "i"; // complete lines to next diff // there is more than 1 diff if (x + 1 < differences.Count) { for (int i = secondIndex; i < Math.Min(differences[x + 1].deletedIndex - linesLevel, differences[x + 1].insertedIndex); ++i) { diffRange.Add(secondFile[i]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } } // we are at last diff else { for (int i = firstIndex; i < firstFile.Count; ++i) { diffRange.Add(firstFile[i]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } } } // 3. if deleted > inserted if (res > 0) { if (lastAction.Equals("i")) { linesLevel *= -1; } // complete start lines to first file for (int i = firstIndex; i < differences[x].deletedIndex; ++i) { diffRange.Add(firstFile[i]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } // if there is some changed lines if (differences[x].insertedAmount > 0) { // we add changed lines to first file for (int i = 0; i < differences[x].insertedAmount; ++i) { diffRange.Add("-" + firstFile[firstIndex]); diffRange.Add("+" + secondFile[secondIndex]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } } // add deleted lines for (int i = 0; i < differences[x].deletedAmount - differences[x].insertedAmount; ++i) { diffRange.Add("-" + firstFile[firstIndex]); ++firstIndex; ++firstRange; } linesLevel -= res; lastAction = "d"; // complete lines to next diff // there is more than 1 diff if (x + 1 < differences.Count) { for (int i = firstIndex; i < Math.Min(differences[x + 1].deletedIndex, differences[x + 1].insertedIndex - linesLevel); ++i) { diffRange.Add(firstFile[firstIndex]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } } // we are at last diff else { for (int i = firstIndex; i < firstFile.Count; ++i) { diffRange.Add(firstFile[i]); ++firstIndex; ++firstRange; ++secondIndex; ++secondRange; } } } // add range line and collection with lines patch.Add("@@ -" + deletedIndex.ToString() + "," + firstRange.ToString() + " +" + insertedIndex.ToString() + "," + secondRange.ToString() + " @@"); patch.AddRange(diffRange); // Clear diffrange collection diffRange.Clear(); // init variables firstRange = secondRange = 0; } } return patch; }
/// <summary> /// Incapsulates radiolocation image file of a ".rl8" format /// </summary> public Rl8(FileProperties properties, Headers.Abstract.LocatorFileHeader header, RlViewer.Navigation.NavigationContainer navi) : base(properties, header, navi) { _header = header as RlViewer.Headers.Concrete.Rl8.Rl8Header; }
private void TestFilePropertiesClone(FileProperties fp) { // Set members in source object fp.ContentType = "foo_1"; fp.ContentEncoding = "foo_2"; fp.Headers = new Dictionary<string, object>(); fp.Headers.Add("foo_3", "foo_4"); fp.Headers.Add("foo_5", "foo_6"); fp.Priority = 12; fp.ReplyTo = "foo_7"; fp.MessageId = "foo_8"; fp.Filename = "foo_9"; fp.Timestamp = new AmqpTimestamp(123); fp.ClusterId = "foo_10"; // Clone FileProperties fpClone = fp.Clone() as FileProperties; // Change values in source object fp.ContentType = "foo_11"; fp.ContentEncoding = "foo_12"; fp.Headers = new Dictionary<string, object>(); fp.Headers.Add("foo_13", "foo_14"); fp.Headers.Add("foo_15", "foo_16"); fp.Priority = 34; fp.ReplyTo = "foo_17"; fp.MessageId = "foo_18"; fp.Filename = "foo_19"; fp.Timestamp = new AmqpTimestamp(234); fp.ClusterId = "foo_20"; // Make sure values have not changed in clone Assert.AreEqual("foo_1", fpClone.ContentType); Assert.AreEqual("foo_2", fpClone.ContentEncoding); Assert.AreEqual(2, fpClone.Headers.Count); Assert.AreEqual(true, fpClone.Headers.ContainsKey("foo_3")); Assert.AreEqual("foo_4", fpClone.Headers["foo_3"]); Assert.AreEqual(true, fpClone.Headers.ContainsKey("foo_5")); Assert.AreEqual("foo_6", fpClone.Headers["foo_5"]); Assert.AreEqual(12, fpClone.Priority); Assert.AreEqual("foo_7", fpClone.ReplyTo); Assert.AreEqual("foo_8", fpClone.MessageId); Assert.AreEqual("foo_9", fpClone.Filename); Assert.AreEqual(new AmqpTimestamp(123), fpClone.Timestamp); Assert.AreEqual("foo_10", fpClone.ClusterId); }
public static FileInformation GetInformation(Stream stream, FileProperties requiredProperties) => new FileInformation().AddProperties(stream, requiredProperties);