/// <summary> /// Creates a new No Change editor, which displays the text in the NewGenFile of the file passed to it. /// </summary> /// <param name="textFileInfo">The text file to display.</param> public ucNoChangeEditor(FileInformation<string> textFileInfo) { InitializeComponent(); if (textFileInfo == null) { throw new InvalidOperationException("Cannot initialise the NoChangeEditor with a null TextFileInformation object."); } //if (textFileInfo.CurrentDiffResult.DiffType != TypeOfDiff.ExactCopy) //{ // throw new Exception("This control is only inteneded to be used for files no changes."); //} IProjectFile<string> file = textFileInfo.MergedFileExists ? textFileInfo.MergedFile : textFileInfo.UserFile; if(file == null || file.HasContents == false) { if (textFileInfo.NewGenFile == null || textFileInfo.NewGenFile.HasContents == false) { throw new InvalidOperationException("The user and newly generated file do not exist, so the control has nothing to display."); } file = textFileInfo.NewGenFile; } syntaxEditor.Text = file.GetContents(); syntaxEditor.Document.Language = SyntaxEditorHelper.GetSyntaxLanguageFromFileName(textFileInfo.RelativeFilePath); warningLabel.MaximumSize = new System.Drawing.Size(Size.Width, 0); warningLabel.Text = ""; }
public ThreeWayVisualDiff(FileInformation<string> tfi) { if (tfi == null) throw new ArgumentNullException("tfi"); fileInfo = tfi; prevgen = ExtractFileToStringList(fileInfo.PrevGenFile); user = ExtractFileToStringList(fileInfo.UserFile); newgen = ExtractFileToStringList(fileInfo.NewGenFile); }
private static void CreateFile(SQLiteCommand cmd, FileInformation file, long? folderId) { cmd.Parameters["@name"].Value = file.Name; cmd.Parameters["@folder"].Value = folderId; cmd.Parameters["@size"].Value = file.FileSize; cmd.Parameters["@createDate"].Value = file.CreationTime; cmd.Parameters["@lastWriteDate"].Value = file.LastWriteTime; cmd.ExecuteNonQuery(); }
private Task CreateTask(FileInformation info) { var task = new Task(() => { if (AddInformationToTheDb(info.FullPath)) { Console.WriteLine("File " + info.FullPath + " is recorded!"); } else { Console.WriteLine("In the process of writing a file error occurred!"); } }); task.Start(); return task; }
private void bgWorker_DoWork(object sender, DoWorkEventArgs e) { BindingList<FileInformation> data = new BindingList<FileInformation>(); if (e.Argument is KeyValuePair<HashHelper.HashType, List<string>>) { List<string> files = ((KeyValuePair<HashHelper.HashType, List<string>>)e.Argument).Value; HashHelper.HashType type = ((KeyValuePair<HashHelper.HashType, List<string>>)e.Argument).Key; foreach (string file in files) { FileInfo fileInf = new FileInfo(file); FileInformation inf = new FileInformation(); inf.Name = fileInf.Name; bgWorker.ReportProgress(0, fileInf.Name); inf.Path = fileInf.FullName; inf.Hash = HashHelper.GetFileHash(file, type); inf.FileDate = fileInf.LastWriteTime; inf.FileSize = (Int64)fileInf.Length/1000; data.Add(inf); } } e.Result = data; }
private void buttonOK_Click(object sender, EventArgs e) { Result = null; using (new WaitCursor(this, WaitCursorOption.ShortSleep)) { var cultures = getCultures(); var baseFolderPath = baseFolderTextEdit.Text.Trim(); var baseFileName = baseFileNameTextEdit.Text.Trim(); var extension = @"." + extensionComboBoxEdit.Text.Trim('.'); var created = 0; using (new BackgroundWorkerLongProgressGui( delegate(object snd, DoWorkEventArgs args) { try { var bw = (BackgroundWorker)snd; // -- // First pass, add all in-memory to check for same file group. var fg = new FileGroup(_project); if (cultures != null) { foreach (var culture in cultures) { var fileName = _project.IsNeutralLanguage(culture) ? baseFileName + extension : generateFileName(fg, culture); fg.Add(new FileInformation(fg) { File = new ZlpFileInfo(fileName) }); } // Look for same entries. if (_project.FileGroups.HasFileGroupWithChecksum( fg.GetChecksum(_project))) { throw new MessageBoxException( this, Resources.SR_ProjectFilesUserControl_AddResourceFilesWithDialog_ExistsInTheProject, MessageBoxIcon.Information); } else { // -- // Second pass, add all existing. fg = new FileGroup(_project); foreach (var culture in cultures) { if (bw.CancellationPending) { throw new OperationCanceledException(); } var fileName = _project.IsNeutralLanguage(culture) ? baseFileName + extension : generateFileName(fg, culture); FileInformation ffi; if (_project.IsNeutralLanguage(culture)) { ffi = new FileInformation(fg) { File = new ZlpFileInfo(ZlpPathHelper.Combine(baseFolderPath, fileName)) }; fg.Add(ffi); } else { ffi = fg.CreateAndAddNewFile( baseFolderPath, fileName, culture.Name); } // Must create real file. ZlpIOHelper.WriteAllText(ffi.File.FullName, Resources.SR_EmptyResourceFile); created++; } } } if (_projectFolder != null) { fg.ProjectFolder = _projectFolder; } _project.FileGroups.Add(fg); _project.MarkAsModified(); Result = fg; } catch (OperationCanceledException) { // Ignore. } }, Resources.SR_CreateNewFilesForm_Creating, BackgroundWorkerLongProgressGui.CancellationMode.Cancelable, this)) { } // -- XtraMessageBox.Show( this, string.Format( Resources.SR_CreateNewFilesForm_Finished03, created), @"Zeta Resource Editor", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
private void _FormDragDrop_internal(object sender, DragEventArgs e) { /* * Refactor, moving the loading of particular files into separate functions that can * then be used by this code, and loading individual files through the file dialogue. * * Step 1: * Build a dictionary of relevant files from everything that was dragged and dropped. * This includes peeking into all relevant archives and using their files. * * Step 2: * Perhaps ask the user which of a particular file type they want to use. * Example: rom1.nes, rom2.smc, rom3.cue are drag-dropped, ask the user which they want to use. * * Step 3: * Load all of the relevant files, in priority order: * 1) The ROM * 2) State * 3) Watch files * 4) Code Data Logger (CDL) * 5) LUA sessions * 6) LUA scripts * 7) Cheat files * 8) Movie Playback Files * * Bonus: * Make that order easy to change in the code, heavily suggesting ROM and playback as first and last respectively. */ var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); Dictionary <LoadOrdering, List <FileInformation> > sortedFiles = new Dictionary <LoadOrdering, List <FileInformation> >(); // Initialize the dictionary's lists. foreach (LoadOrdering value in Enum.GetValues(typeof(LoadOrdering))) { sortedFiles.Add(value, new List <FileInformation>()); } ProcessFileList(HawkFile.Util_ResolveLinks(filePaths), ref sortedFiles, null); // For each of the different types of item, if there are no items of that type, skip them. // If there is exactly one of that type of item, load it. // If there is more than one, ask. foreach (LoadOrdering value in Enum.GetValues(typeof(LoadOrdering))) { switch (sortedFiles[value].Count) { case 0: break; case 1: FileInformation fileInformation = sortedFiles[value].First <FileInformation>(); string filename = Path.Combine(new string[] { fileInformation.directoryName, fileInformation.fileName }); switch (value) { case LoadOrdering.ROM: _LoadRom(filename, fileInformation.archiveName); break; case LoadOrdering.STATE: _LoadState(filename, fileInformation.archiveName); break; case LoadOrdering.WATCH: _LoadWatch(filename, fileInformation.archiveName); break; case LoadOrdering.CDLFILE: _LoadCDL(filename, fileInformation.archiveName); break; case LoadOrdering.LUASESSION: _LoadLuaSession(filename, fileInformation.archiveName); break; case LoadOrdering.LUASCRIPT: _LoadLuaFile(filename, fileInformation.archiveName); break; case LoadOrdering.CHEAT: _LoadCheats(filename, fileInformation.archiveName); break; case LoadOrdering.MOVIEFILE: case LoadOrdering.LEGACYMOVIEFILE: // I don't really like this hack, but for now, we only want to load one movie file. if (sortedFiles[LoadOrdering.MOVIEFILE].Count + sortedFiles[LoadOrdering.LEGACYMOVIEFILE].Count > 1) { break; } if (value == LoadOrdering.MOVIEFILE) { _LoadMovie(filename, fileInformation.archiveName); } else { _LoadLegacyMovie(filename, fileInformation.archiveName); } break; } break; default: break; } } }
public int FindFiles(string sPath, System.Collections.ArrayList FoundFiles, DokanFileInfo DFI) { sPath = sPath.Replace("\\", "/"); string[] sDirectoryListing; try { sDirectoryListing = AFC.ListDirectory(sPath); } catch (FileNotFoundException) { return -DokanNet.ERROR_PATH_NOT_FOUND; } catch (Exception) { return -1; } sPath += "/"; foreach (string sItem in sDirectoryListing) { if (sItem == "." || sItem == ".." || String.IsNullOrEmpty(sItem)) continue; string sFileInfo; try { sFileInfo = AFC.GetFileInfo(sPath + sItem); } catch (Exception) { continue; } string[] sFileInfoParts = sFileInfo.Split(new char[] { '\x0' }); string sFileType = null; string sFileLength = null; for (int i = 0; i < sFileInfoParts.Length; i++) { if (sFileInfoParts[i] == "st_size" && i < (sFileInfoParts.Length - 1)) sFileLength = sFileInfoParts[i + 1]; else if (sFileInfoParts[i] == "st_ifmt" && i < (sFileInfoParts.Length - 1)) sFileType = sFileInfoParts[i + 1]; } FileInformation FI = new FileInformation(); FI.FileName = sItem; FI.LastAccessTime = DateTime.Now; FI.LastWriteTime = DateTime.Now; FI.CreationTime = DateTime.Now; if (sFileLength != null) FI.Length = long.Parse(sFileLength); switch (sFileType) { case "S_IFLNK": case "S_IFDIR": FI.Length = 0; FI.Attributes = FileAttributes.Directory; break; case "S_IFREG": FI.Attributes = FileAttributes.Normal; break; default: FI.Attributes = FileAttributes.Normal; break; } FoundFiles.Add(FI); } return 0; }
private static void ProcessUserChange(FileInformation<string> fileInfo, VisualDiffOutput output) { string[] newlines = Common.Utility.StandardizeLineBreaks(fileInfo.UserFile.GetContents(), Common.Utility.LineBreaks.Unix).Split('\n'); ProcessSingleChange(fileInfo, output, newlines, ChangeType.User); }
public LoadFileWrapper(IDisplayBinding binding, Project project, FileInformation fileInfo) { this.fileInfo = fileInfo; this.binding = binding; this.project = project; }
/// <summary> /// Take a TextFileInformation object, diff it if it hasn't been diffed, and create a VisualDiffOutput object that /// represents the output of the diff in a form that can be displayed to the user. /// </summary> /// <remarks> /// If the Prevgen file does not exist, it will perform a diff, then copy the NewGen file into the PrevGen temporarily, /// so that all changes will show as User changes. /// </remarks> /// <param name="fileInfo">The TextFileInformation object that has the information on the diffed files.</param> /// <returns>A VisualDiffOutput object containing all of the information needed to show the output of the diff to the user.</returns> private VisualDiffOutput ProcessDiff(FileInformation<string> fileInfo) { if (fileInfo == null) throw new ArgumentNullException("fileInfo"); VisualDiffOutput output = new VisualDiffOutput(); bool virtualPrevGen = false; string oldPrevGenFilePath = null; if (fileInfo.CurrentDiffResult.DiffPerformedSuccessfully == false) fileInfo.PerformDiff(); if (fileInfo.PrevGenFile.HasContents == false) { virtualPrevGen = true; oldPrevGenFilePath = fileInfo.PrevGenFile.FilePath; fileInfo.PrevGenFile.ReplaceContents(fileInfo.NewGenFile.GetContents(), true); } output.DiffType = fileInfo.CurrentDiffResult.DiffType; switch (fileInfo.CurrentDiffResult.DiffType) { case TypeOfDiff.ExactCopy: ProcessExactCopy(fileInfo, output); break; case TypeOfDiff.TemplateChangeOnly: ProcessTemplateChange(fileInfo, output); break; case TypeOfDiff.UserChangeOnly: ProcessUserChange(fileInfo, output); break; case TypeOfDiff.UserAndTemplateChange: ProcessUserAndTemplateChange(fileInfo, output); break; case TypeOfDiff.Conflict: case TypeOfDiff.Warning: ProcessUserAndTemplateChange(fileInfo, output); break; } if (virtualPrevGen) { fileInfo.PrevGenFile.FilePath = oldPrevGenFilePath; if (oldPrevGenFilePath != null) { fileInfo.PrevGenFile.ReplaceContents("", false); } } return output; }
private void GetFileList(DirectoryInfo directory) { SelectFile(-1); currentDirectory = directory; parentDirectory = new DirectoryInformation(directory.Parent ?? directory, backTexture); showDrives = directory.Parent == null; var driveNames = Directory.GetLogicalDrives(); drives = new DirectoryInformation[driveNames.Length]; for (var i = 0; i < drives.Length; i++) drives[i] = new DirectoryInformation(new DirectoryInfo(driveNames[i]), driveTexture); var directoryInfos = directory.GetDirectories(); directories = new DirectoryInformation[directoryInfos.Length]; for (var i = 0; i < directories.Length; i++) directories[i] = new DirectoryInformation(directoryInfos[i], directoryTexture); var fileInfos = directory.GetFiles(); files = new FileInformation[fileInfos.Length]; for (var i = 0; i < files.Length; i++) files[i] = new FileInformation(fileInfos[i], fileTexture); }
/// <remarks> /// Support for pass-through Information Levels must be enabled. /// </remarks> public FileInformation GetFileInformation(FileInformationClass informationClass) { return(FileInformation.GetFileInformation(InformationBytes, 0, informationClass)); }
/// <summary> /// Get the file information for the document attached to the ifcRelAssociatesDocument /// </summary> /// <param name="ifcRelAssociatesDocument">IfcRelAssociatesDocument object</param> /// <returns>FileInformation structure </returns> private FileInformation GetFileInformation(IfcRelAssociatesDocument ifcRelAssociatesDocument) { FileInformation DocInfo = new FileInformation() { Name = DEFAULT_STRING, Location = DEFAULT_STRING }; string value = ""; if (ifcRelAssociatesDocument != null) { //test for single document IfcDocumentReference ifcDocumentReference = ifcRelAssociatesDocument.RelatingDocument as IfcDocumentReference; if (ifcDocumentReference != null) { //this is possibly incorrect, think it references information within a document value = ifcDocumentReference.ItemReference.ToString(); if (!string.IsNullOrEmpty(value)) { DocInfo.Name = value; } value = ifcDocumentReference.Location.ToString(); if (!string.IsNullOrEmpty(value)) { DocInfo.Location = value; } } else //test for a document list { IfcDocumentInformation ifcDocumentInformation = ifcRelAssociatesDocument.RelatingDocument as IfcDocumentInformation; if (ifcDocumentInformation != null) { IEnumerable <IfcDocumentReference> ifcDocumentReferences = ifcDocumentInformation.DocumentReferences; if (ifcDocumentReferences != null) { List <string> strNameValues = new List <string>(); List <string> strLocationValues = new List <string>(); foreach (IfcDocumentReference docRef in ifcDocumentReferences) { //get file name value = docRef.ItemReference.ToString(); if (!string.IsNullOrEmpty(value)) { strNameValues.Add(value); } else { value = docRef.Name.ToString(); if (!string.IsNullOrEmpty(value)) { strNameValues.Add(value); } } //get file location value = docRef.Location.ToString(); if ((!string.IsNullOrEmpty(value)) && (!strNameValues.Contains(value))) { strLocationValues.Add(value); } } //set values to return if (strNameValues.Count > 0) { DocInfo.Name = COBieXBim.JoinStrings(':', strNameValues); } if (strLocationValues.Count > 0) { DocInfo.Location = COBieXBim.JoinStrings(':', strLocationValues); } } } } } return(DocInfo); }
/// <summary> /// Fill sheet rows for Document sheet /// </summary> /// <returns>COBieSheet</returns> public override COBieSheet <COBieDocumentRow> Fill() { ProgressIndicator.ReportMessage("Starting Documents..."); //create new sheet COBieSheet <COBieDocumentRow> documents = new COBieSheet <COBieDocumentRow>(Constants.WORKSHEET_DOCUMENT); // get all IfcBuildingStory objects from IFC file IEnumerable <IfcDocumentInformation> docInfos = Model.Instances.OfType <IfcDocumentInformation>(); ProgressIndicator.Initialise("Creating Documents", docInfos.Count()); foreach (IfcDocumentInformation di in docInfos) { ProgressIndicator.IncrementAndUpdate(); COBieDocumentRow doc = new COBieDocumentRow(documents); doc.Name = (di == null) ? "" : di.Name.ToString(); //get the first associated document to extract the objects the document refers to IfcRelAssociatesDocument ifcRelAssociatesDocument = DocumentInformationForObjects(di).FirstOrDefault(); if ((ifcRelAssociatesDocument != null) && (ifcRelAssociatesDocument.OwnerHistory != null)) { doc.CreatedBy = GetTelecomEmailAddress(ifcRelAssociatesDocument.OwnerHistory); } else if (di.DocumentOwner != null) { if (di.DocumentOwner is IfcPersonAndOrganization) { doc.CreatedBy = GetTelecomEmailAddress(di.DocumentOwner as IfcPersonAndOrganization); } else if (di.DocumentOwner is IfcPerson) { doc.CreatedBy = GetEmail(null, di.DocumentOwner as IfcPerson); } else if (di.DocumentOwner is IfcOrganization) { doc.CreatedBy = GetEmail(di.DocumentOwner as IfcOrganization, null); } } else if ((Model.IfcProject as IfcRoot).OwnerHistory != null) { doc.CreatedBy = GetTelecomEmailAddress((Model.IfcProject as IfcRoot).OwnerHistory); } if ((ifcRelAssociatesDocument != null) && (ifcRelAssociatesDocument.OwnerHistory != null)) { doc.CreatedOn = GetCreatedOnDateAsFmtString(ifcRelAssociatesDocument.OwnerHistory); } else if (di.CreationTime != null) { doc.CreatedOn = di.CreationTime.ToString(); } else if ((Model.IfcProject as IfcRoot).OwnerHistory != null) { doc.CreatedOn = Context.RunDateTime; } doc.Category = (string.IsNullOrEmpty(di.Purpose.ToString())) ? DEFAULT_STRING :di.Purpose.ToString(); doc.ApprovalBy = (string.IsNullOrEmpty(di.IntendedUse.ToString())) ? DEFAULT_STRING : di.IntendedUse.ToString(); doc.Stage = (string.IsNullOrEmpty(di.Scope.ToString())) ? DEFAULT_STRING : di.Scope.ToString(); RelatedObjectInformation relatedObjectInfo = GetRelatedObjectInformation(ifcRelAssociatesDocument); doc.SheetName = relatedObjectInfo.SheetName; doc.RowName = relatedObjectInfo.Name; doc.ExtObject = relatedObjectInfo.ExtObject; doc.ExtIdentifier = relatedObjectInfo.ExtIdentifier; doc.ExtSystem = relatedObjectInfo.ExtSystem; FileInformation fileInfo = GetFileInformation(ifcRelAssociatesDocument); doc.File = fileInfo.Name; doc.Directory = GetDirectory(!string.IsNullOrWhiteSpace(fileInfo.Location) ? fileInfo.Location : fileInfo.Name); doc.Description = (string.IsNullOrEmpty(di.Description)) ? DEFAULT_STRING : di.Description.ToString(); doc.Reference = (string.IsNullOrEmpty(di.DocumentId.Value.ToString())) ? DEFAULT_STRING : di.DocumentId.Value.ToString(); documents.AddRow(doc); } documents.OrderBy(s => s.Name); ProgressIndicator.Finalise(); return(documents); }
static void Main(string[] args) { FileInfo = new FileInformation(); while (ValueFormatter.isEmpty(FileInfo.InputFileName)) { Out.WriteLine("Please copy and paste file path in .csv or .tsv format"); FileInfo.InputFileName = ReadLine(); } FileInfo.ReadResults = GetFileName.ReadFileName(FileInfo.InputFileName); string numberOfFields = null; int temp2; while (ValueFormatter.isEmpty(numberOfFields) || !int.TryParse(numberOfFields, out temp2)) { WriteLine("Enter number of fields"); numberOfFields = ReadLine(); } int fieldsInRecords = 0; try { fieldsInRecords = Convert.ToInt32(numberOfFields); FileInfo.NumberOfFields = fieldsInRecords; FileInfo.Results = GetLines.ReturnDetailRecords(FileInfo.ReadResults); FileInfo.NewResults = FileInfo.Results.Skip(1).ToList(); char delimiter = GetFileName.CheckFileName(FileInfo.InputFileName); //Once you run this, it'll write the files to your bin direcotry FileInfo.EnvironmentDirectory = WriteToFile.GetEnvironmentDirectory(); foreach (var rec in FileInfo.NewResults) { var returnedFields = GetLines.ReturnFields(rec, delimiter); var isRecordCorrect = GetLines.GetFieldCount(returnedFields, fieldsInRecords); if (isRecordCorrect == false) { var pathCombined = Path.Combine(FileInfo.EnvironmentDirectory, "errorrecs.txt"); Out.WriteLine($"directory is {pathCombined}"); WriteToFile.WriteErrorsToFile(pathCombined, rec); } else { var pathCombined = Path.Combine(FileInfo.EnvironmentDirectory, "correct.txt"); Out.WriteLine($"directory is {pathCombined}"); WriteToFile.WriteErrorsToFile(pathCombined, rec); } } Console.WriteLine($"the delimiter is {delimiter}"); Console.WriteLine(FileInfo.NewResults.Count); } catch (System.FormatException fe) { Out.WriteLine($"No fields were read {fe}"); } Console.Out.WriteLine("Bonsoir, Elliot"); Console.ReadKey(); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var path = value as string; return(FileInformation.LoadBitmapImage(path)); }
/// <summary> /// Initialize a file for upload /// </summary> /// <returns>Token that is used to append data in chunk</returns> public FileDataInfo SendFileStart(FileInformation block) { if (block == null) { throw new Exception("Fie information not set"); } if (block.TenantID == Guid.Empty) { throw new Exception("Invalid Tenant ID"); } if (string.IsNullOrEmpty(block.Container)) { throw new Exception("Invalid container"); } if (string.IsNullOrEmpty(block.FileName)) { throw new Exception("Invalid file name"); } if (block.Size < 0) { throw new Exception("Invalid file size"); } byte[] tenantKey = null; using (var fm = new FileManager()) { var tenant = fm.GetTenant(block.TenantID); tenantKey = tenant.Key.Decrypt(fm.MasterKey, fm.IV); } lock (_fileUploadCache) { var cache = new FilePartCache { TenantID = block.TenantID, Container = block.Container, FileName = block.FileName, CRC = block.CRC, Size = block.Size, Index = 0, CreatedTime = block.CreatedTime, ModifiedTime = block.ModifiedTime, TenantKey = tenantKey, }; //Add to part cache if (_fileUploadCache.Contains(cache.Key)) { throw new Exception("File concurrency error"); } try { using (var fm = new FileManager()) { fm.RemoveFile(block.TenantID, block.Container, block.FileName); } _fileUploadCache.Add(cache.Key); _fileUploadPartCache.TryAdd(cache.ID, cache); using (var fm = new FileManager()) { var header = new FileHeader { DataKey = cache.OneTimeKey, EncryptedDataKey = cache.OneTimeKey.Encrypt(cache.TenantKey, FileEngine.DefaultIVector), TenantKey = cache.TenantKey, }; //Create the data folder var dataPath = Path.Combine(ConfigHelper.WorkFolder, cache.ID.ToString()); Directory.CreateDirectory(dataPath); cache.TempDataFile = Path.Combine(dataPath, "out"); cache.EncryptStream = Extensions.OpenEncryptStream(cache.TempDataFile, fm.IV, header); } return(new FileDataInfo { Token = cache.ID, Size = cache.Size, CreatedTime = block.CreatedTime, ModifiedTime = block.ModifiedTime, }); } catch (Exception ex) { Logger.LogError(ex); throw; } } }
public int GetFileInformation(string filename, FileInformation fileinfo, DokanFileInfo info) { return(this.operation.GetFileInformation(filename, fileinfo, info)); }
private void SearchFile() { isSearching = true; var fileInfos = searchString == "" ? currentDirectory.GetFiles() : currentDirectory.GetFiles(searchString, recursiveSearch ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); files = new FileInformation[fileInfos.Length]; if (fileInfos.Length == 0) selectedIndex = -1; else { for (var i = 0; i < files.Length; i++) files[i] = new FileInformation(fileInfos[i], fileTexture); selectedIndex = 0; } justFinishedSearching = true; }
//Открытие файла | папки private void ClickEvent(IList Files, ComboBox Path) { if (Files.Count == 0) { return; } Boolean PathAlreadyChanged = false; String StdPath = Path.Text; //Копирование коллекции ArrayList SelectedFiles = new ArrayList(); foreach (var x in Files) { SelectedFiles.Add(x); } //"Запуск" файлов foreach (var Item in SelectedFiles) { if (!(Item is FileInformation)) { return; } FileInformation Current = Item as FileInformation; if (Current.FileSize == "Folder") { if ((Current.FileName == ".." || Current.FileName == ".") && !PathAlreadyChanged) { //Идем по папкам назад StringBuilder CurrentPath = new StringBuilder(Path.Text); CurrentPath.Remove(CurrentPath.Length - 1, 1); while (CurrentPath.Length > 0 && CurrentPath[CurrentPath.Length - 1] != '\\' && CurrentPath[CurrentPath.Length - 1] != '/') { CurrentPath.Remove(CurrentPath.Length - 1, 1); if (CurrentPath.Length == 0) { Path.Text = Path.Items[0].ToString(); } } Path.Text = CurrentPath.ToString(); } else//открываем новую папку { if (!PathAlreadyChanged) { Path.Text += Current.FileName + "\\"; } else { Process newProc = new Process(); newProc.StartInfo = new System.Diagnostics.ProcessStartInfo(System.Reflection.Assembly.GetExecutingAssembly().Location); newProc.StartInfo.FileName = System.Reflection.Assembly.GetExecutingAssembly().Location; newProc.StartInfo.Arguments = StdPath + Current.FileName + "\\"; newProc.Start(); } } PathAlreadyChanged = true; } else { try { Process newProc = new Process(); newProc.StartInfo = new System.Diagnostics.ProcessStartInfo(Path.Text + Current.FileName); newProc.StartInfo.WorkingDirectory = Path.Text; newProc.Start(); } catch (Exception) { } } } }
private void AddFileInfo(FileInfo fileInfo) { bool callUpdateEvent = false; lock (resultLock) { if (!resultFiles.ContainsKey(fileInfo.Name.ToLower())) { resultFiles.Add(fileInfo.Name.ToLower(), fileInfo); callUpdateEvent = true; } else { if (resultFiles[fileInfo.Name.ToLower()].LastWriteTime.CompareTo(fileInfo.LastWriteTime) < 0) { resultFiles[fileInfo.Name.ToLower()] = fileInfo; callUpdateEvent = true; } } } if (callUpdateEvent) { var file = new FileInformation( fileInfo.Name, fileInfo.FullName, fileInfo.Extension, fileInfo.DirectoryName, fileInfo.CreationTime, fileInfo.LastAccessTime, fileInfo.LastWriteTime, //TODO: Get local IP from constructor Settings.LOCAL_IP.ToString() ); ListUpdate(file, file.hostIp); } }
public IAsyncOperation OpenFile(string fileName, int line, int column, bool bringToFront) { foreach (IViewContent content in WorkbenchSingleton.Workbench.ViewContentCollection) { if (content.ContentName == fileName || (content.ContentName == null && content.UntitledName == fileName)) { if (bringToFront) content.WorkbenchWindow.SelectWindow(); if (line != -1 && content is IPositionable) { ((IPositionable)content).JumpTo (line, column != -1 ? column : 0); } return NullAsyncOperation.Success; } } IProgressMonitor pm = Runtime.TaskService.GetStatusProgressMonitor (string.Format (GettextCatalog.GetString ("Opening {0}"), fileName), Stock.OpenFileIcon, false); FileInformation openFileInfo = new FileInformation(); openFileInfo.ProgressMonitor = pm; openFileInfo.FileName = fileName; openFileInfo.BringToFront = bringToFront; openFileInfo.Line = line; openFileInfo.Column = column; Runtime.DispatchService.GuiDispatch (new StatefulMessageHandler (realOpenFile), openFileInfo); return pm.AsyncOperation; }
NtStatus IDokanOperations.GetFileInformation(string fileName, out FileInformation fileInfo, DokanFileInfo info) { SftpDrive drive = this.GetDriveByMountPoint(fileName, out fileName); LogFSActionInit("FileInfo", fileName, drive, ""); if (drive != null) { LogFSActionSuccess("FileInfo", fileName, drive, "NonVFS"); return(GetSubSystemOperations(drive).GetFileInformation(fileName, out fileInfo, info)); } fileInfo = new FileInformation { Attributes = FileAttributes.NotContentIndexed | FileAttributes.Directory | FileAttributes.ReparsePoint | FileAttributes.Offline, FileName = Path.GetFileName(fileName), //String.Empty, // GetInfo info doesn't use it maybe for sorting . CreationTime = DateTime.Now, LastAccessTime = DateTime.Now, LastWriteTime = DateTime.Now, Length = 4096 }; if (fileName.Length == 1) { //root dir LogFSActionSuccess("FileInfo", fileName, drive, "root info"); return(NtStatus.Success); } string path = fileName.Substring(1);//cut leading \ if (info.Context != null) { drive = info.Context as SftpDrive; LogFSActionSuccess("FileInfo", fileName, drive, "from context"); return(NtStatus.Success); } foreach (SftpDrive subdrive in _subsytems) { string mp = subdrive.MountPoint; // mp1 || mp1\mp2 ... if (path == mp) { info.Context = mp; //fileInfo.FileName = path.Substring(path.LastIndexOf("\\")+1); LogFSActionSuccess("FileInfo", fileName, drive, "final mountpoint"); return(NtStatus.Success); } if (mp.IndexOf(path + '\\') == 0) { //path is part of mount point //fileInfo.FileName = path.Substring(path.LastIndexOf("\\") + 1); LogFSActionSuccess("FileInfo", fileName, drive, "part of mountpoint"); return(NtStatus.Success); } } LogFSActionError("FileInfo", fileName, drive, "path not found"); return(NtStatus.ObjectPathNotFound); }
private void ProcessFileList(string[] fileList, ref Dictionary<LoadOrdering, List<FileInformation>> sortedFiles, string archive = null) { foreach (string file in fileList) { var ext = Path.GetExtension(file).ToUpper() ?? String.Empty; FileInformation fileInformation = new FileInformation(Path.GetDirectoryName(file), Path.GetFileName(file), archive); switch (ext) { case ".LUA": sortedFiles[LoadOrdering.LUASCRIPT].Add(fileInformation); break; case ".LUASES": sortedFiles[LoadOrdering.LUASESSION].Add(fileInformation); break; case ".STATE": sortedFiles[LoadOrdering.STATE].Add(fileInformation); break; case ".CHT": sortedFiles[LoadOrdering.CHEAT].Add(fileInformation); break; case ".WCH": sortedFiles[LoadOrdering.WATCH].Add(fileInformation); break; case ".CDL": sortedFiles[LoadOrdering.CDLFILE].Add(fileInformation); break; default: if (MovieService.IsValidMovieExtension(ext)) sortedFiles[LoadOrdering.MOVIEFILE].Add(fileInformation); else if (MovieImport.IsValidMovieExtension(ext)) sortedFiles[LoadOrdering.LEGACYMOVIEFILE].Add(fileInformation); else if (knownROMExtensions.Contains(ext)) { if (String.IsNullOrEmpty(archive) || !nonArchive.Contains(ext)) sortedFiles[LoadOrdering.ROM].Add(fileInformation); } else { /* Because the existing behaviour for archives is to try loading * ROMs out of them, that is exactly what we are going to continue * to do at present. Ideally, the archive should be scanned and * relevant files should be extracted, but see the note below for * further details. */ int offset = 0; bool executable = false; var archiveHandler = new SevenZipSharpArchiveHandler(); if (String.IsNullOrEmpty(archive) && archiveHandler.CheckSignature(file, out offset, out executable)) sortedFiles[LoadOrdering.ROM].Add(fileInformation); /* * This is where handling archives would go. * Right now, that's going to be a HUGE hassle, because of the problem with * saving things into the archive (no) and with everything requiring filenames * and not streams (also no), so for the purposes of making drag/drop more robust, * I am not building this out just yet. * -- Adam Michaud (Invariel) int offset = 0; bool executable = false; var archiveHandler = new SevenZipSharpArchiveHandler(); // Not going to process nested archives at the moment. if (String.IsNullOrEmpty (archive) && archiveHandler.CheckSignature(file, out offset, out executable)) { List<string> fileNames = new List<string>(); var openedArchive = archiveHandler.Construct (file); foreach (BizHawk.Common.HawkFileArchiveItem item in openedArchive.Scan ()) fileNames.Add(item.Name); ProcessFileList(fileNames.ToArray(), ref sortedFiles, file); openedArchive.Dispose(); } archiveHandler.Dispose(); */ } break; } } }
NtStatus IDokanOperations.FindStreams(string fileName, out IList <FileInformation> streams, DokanFileInfo info) { streams = new FileInformation[0]; return(NtStatus.NotImplemented); }
/// <summary>Gera uma lista lista dos arquivos contidos num determinado diretório</summary> /// <summary>Pega informação sobre tipo e codificação do arquivo</summary> /// <param name="b">Caminho do diretório desejado</param> /// <returns>Stringlist com os caminhos dos arquivos existentes no diretório</returns> public List<FileInformation> DirectoryGetFilesInfoRecusive(string b) { bool binaryExtensionFound=false; // 1. // Store results in the file results list. List<FileInformation> result = new List<FileInformation>(); // 2. // Store a stack of our directories. Stack<string> stack = new Stack<string>(); // 3. // Add initial directory. stack.Push(b); // 4. // Continue while there are directories to process while (stack.Count > 0) { // A. // Get top directory string dir = stack.Pop(); try { // B // Add all files at this directory to the result List. //Era o original //result.AddRange(Directory.GetFiles(dir, "*.*")); foreach (string s in Directory.GetFiles(dir, "*.*")) { FileInformation fi = new FileInformation(); fi.Path = s; FileInfo info = new FileInfo(s); fi.size = info.Length; //1st check it the file has a common type of binary extension binaryExtensionFound = false; foreach (string extension in BinaryExtensions) { if (s.ToLower().EndsWith(extension)) { binaryExtensionFound = true; break; } } if (binaryExtensionFound) { fi.Encoding = null; fi.Text = false; } else { fi.Text = true; try { Fcn.TryToDetectEncoding(out fi.Encoding, s, 500); } catch (Exception e) { //Colocar log de erro aqui!!! } } result.Add(fi); } // C // Add all directories at this directory. foreach (string dn in Directory.GetDirectories(dir)) { stack.Push(dn); } } catch(Exception ex) { // D //Colocar log de erro aqui!!! //MessageBox.Show(ex.Message);bbbbb } } return result; }
public void Export(WebAssignSettings WebAssignSettings, UserSettings UserSettings, Courses myCourses) { //========================================================== // // IN: UserInfo - user specific Options // myCourses - contains the courses to export // // Returns: Nothing - Events are raised to send status messages // // DESCRIPTION // This procedure exports to an WebAssign upload files //========================================================== bool DeleteFileError; // Verify that WebAssign is to be exported if (!WebAssignSettings.Export) { return; } // Create Directory if it does not exist if (!Directory.Exists(WebAssignSettings.Directory)) { Directory.CreateDirectory(WebAssignSettings.Directory); } // waUserNames contain a list of all WebAssign Usernames as they must // be unique Dictionary <String, int> waUserNames = new Dictionary <String, int>(); try { foreach (Course C in myCourses) { waUserNames.Clear(); if (C.Export) { StringBuilder sbCourse = new StringBuilder(2880); // 72 character per student * 40 students StringBuilder sbStudent = new StringBuilder(2880); // 72 character per student * 40 students string StrSEPERATOR_TYPE; string StrUserName = ""; string StrFullName = ""; string StrUserPassword = ""; SendMessage(this, new Information("Exporting " + C.Name)); if (WebAssignSettings.SEPARATOR == WebAssignSeperator.Tab) { StrSEPERATOR_TYPE = "\t"; } // see escape characters in help else { StrSEPERATOR_TYPE = ","; } int StudentCount = C.Students.Length; // this is a 1 dimensional array for (int i = 0; i < StudentCount; i++) { Student S = C.Students[i]; switch (WebAssignSettings.Username) { case WebAssignUserName.First_Name_Initial_plus_Last_Name: StrUserName = S.FirstName.Substring(0, 1) + S.LastName; break; case WebAssignUserName.First_Name_plus_Last_Name: StrUserName = S.FirstName + S.LastName; break; case WebAssignUserName.First_Name_Initial_plus_Middle_Initial_plus_Last_Name: StrUserName = S.FirstName.Substring(0, 1); if ((S.MiddleName != null) && (S.MiddleName != "")) { StrUserName += S.MiddleName.Substring(0, 1); } StrUserName += S.LastName; break; default: break; } StrUserName = StripIllegalCharacters(StrUserName); StrFullName = S.LastName + ", " + S.FirstName; if (WebAssignSettings.UserPassword == WebAssignPassword.SID) { StrUserPassword = S.SID; } else { StrUserPassword = S.LastName; } if (waUserNames.ContainsKey(StrUserName)) { string msg = "Username for " + StrFullName + " already exists. Replacing '" + StrUserName + "' with "; int NewStudentIndex = 1; do { // Username has already been used - try and create a new one switch (WebAssignSettings.Username) { case WebAssignUserName.First_Name_Initial_plus_Last_Name: StrUserName = S.FirstName.Substring(0, 1) + NewStudentIndex + "." + S.LastName; break; case WebAssignUserName.First_Name_plus_Last_Name: StrUserName = S.FirstName + NewStudentIndex + "." + S.LastName; break; case WebAssignUserName.First_Name_Initial_plus_Middle_Initial_plus_Last_Name: StrUserName = S.FirstName.Substring(0, 1); if ((S.MiddleName != null) && (S.MiddleName != "")) { StrUserName += S.MiddleName.Substring(0, 1); } StrUserName += NewStudentIndex + "." + S.LastName; break; default: break; } NewStudentIndex++; } while (waUserNames.ContainsKey(StrUserName)); StrUserName = StripIllegalCharacters(StrUserName); if (waUserNames.ContainsKey(StrUserName)) { // use full name StrUserName = S.FirstName; if ((S.MiddleName != null) && (S.MiddleName != "")) { StrUserName += "." + S.MiddleName; } StrUserName += "." + S.LastName; StrUserName = StripIllegalCharacters(StrUserName); } if (waUserNames.ContainsKey(StrUserName)) { // ERROR msg += "Unable to calculate a unique user name for " + StrUserName + "'. Using full name."; } else { msg += "'" + StrUserName + "'."; waUserNames.Add(StrUserName, 1); } SendMessage(this, new Information(msg)); } else { waUserNames.Add(StrUserName, 1); } // Eliminate illegal character (-) from username and password string StrWebassignUserName = StripIllegalCharacters(StrUserName).ToLower(); string StrWebassignPassword = StripIllegalCharacters(StrUserPassword).ToLower(); sbCourse.Append(StrWebassignUserName + StrSEPERATOR_TYPE); // username sbCourse.Append(StrFullName.ToLower() + StrSEPERATOR_TYPE); // fullname //sbCourse.Append( StrWebassignPassword + StrSEPERATOR_TYPE); // password sbCourse.Append(S.Email.ToLower() + StrSEPERATOR_TYPE); // email sbCourse.Append(StripIllegalCharacters(S.SID).ToLower() + "\r\n"); // SID int intInstitutionHeader = 0; int intUserNameHeader = 0; int intPasswordHeader = 0; int intInstitutionUser = 0; int intUserNameUser = 0; int intPasswordUser = 0; int intSpacer = 0; string StrInstitutionHeader = "Institution"; string StrUserNameHeader = "Username"; string StrPasswordHeader = "Password"; string StrInstitution = WebAssignSettings.Institution; int intFillnameSpacer = 0; // Adjust the header/user spaces if (StrUserNameHeader.Length > StrUserName.Length) { intUserNameHeader = 0; intUserNameUser = StrUserNameHeader.Length - StrWebassignUserName.Length; } else { intUserNameHeader = StrWebassignUserName.Length - StrUserNameHeader.Length; intUserNameUser = 0; } if (StrInstitutionHeader.Length > StrInstitution.Length) { intInstitutionHeader = 0; intInstitutionUser = StrInstitutionHeader.Length - StrInstitution.Length; } else { intInstitutionHeader = StrInstitution.Length - StrInstitutionHeader.Length; intInstitutionUser = 0; } if (StrPasswordHeader.Length > StrUserPassword.Length) { intPasswordHeader = 0; intPasswordUser = StrPasswordHeader.Length - StrWebassignPassword.Length; } else { intPasswordHeader = StrWebassignPassword.Length - StrPasswordHeader.Length; intPasswordUser = 0; } intSpacer = 10 + StrInstitutionHeader.Length + intInstitutionHeader + StrUserNameHeader.Length + intUserNameHeader + StrPasswordHeader.Length + intPasswordHeader; string StrSpacer = new String('-', intSpacer); // For intLoop = 0 To intSpacer // StrSpacer = StrSpacer & "-" // Next if ((intSpacer - 3) > StrFullName.Length) { intFillnameSpacer = (intSpacer - StrFullName.Length) - 4; } else { intFillnameSpacer = 0; } sbStudent.Append(StrSpacer + "\r\n"); sbStudent.Append("| " + StrFullName + new String(' ', intFillnameSpacer) + " |" + "\r\n"); sbStudent.Append(StrSpacer + "\r\n"); sbStudent.Append("| " + StrUserNameHeader + new String(' ', intUserNameHeader) + " | " + StrInstitutionHeader + new String(' ', intInstitutionHeader) + " | " + StrPasswordHeader + new String(' ', intPasswordHeader) + " |" + "\r\n\r\n"); sbStudent.Append("| " + StrWebassignUserName.ToLower() + new String(' ', intUserNameUser) + " | " + StrInstitution + new String(' ', intInstitutionUser) + " | " + StrWebassignPassword.ToLower() + new String(' ', intPasswordUser) + " |" + "\r\n"); sbStudent.Append(StrSpacer + "\r\n\r\n\r\n"); } // Add Waitlist if (WebAssignSettings.ExportWaitlist) { SendMessage(this, new Information("Exporting " + C.Name + " Waitlist")); int WaitlistCount = C.Waitlist.Length; // this is a 1 dimensional array for (int i = 0; i < WaitlistCount; i++) { Student S = C.Waitlist[i]; switch (WebAssignSettings.Username) { case WebAssignUserName.First_Name_Initial_plus_Last_Name: StrUserName = S.FirstName.Substring(0, 1) + S.LastName; break; case WebAssignUserName.First_Name_plus_Last_Name: StrUserName = S.FirstName + S.LastName; break; case WebAssignUserName.First_Name_Initial_plus_Middle_Initial_plus_Last_Name: StrUserName = S.FirstName.Substring(0, 1); if ((S.MiddleName != null) && (S.MiddleName != "")) { StrUserName += S.MiddleName.Substring(0, 1); } StrUserName += S.LastName; break; default: break; } StrUserName = StripIllegalCharacters(StrUserName); StrFullName = S.LastName + ", " + S.FirstName; if (WebAssignSettings.UserPassword == WebAssignPassword.SID) { StrUserPassword = S.SID; } else { StrUserPassword = S.LastName; } if (waUserNames.ContainsKey(StrUserName)) { string msg = "Username for " + StrFullName + " already exists. Replacing '" + StrUserName + "' with "; int NewStudentIndex = 1; do { // Username has already been used - try and create a new one switch (WebAssignSettings.Username) { case WebAssignUserName.First_Name_Initial_plus_Last_Name: StrUserName = S.FirstName.Substring(0, 1) + NewStudentIndex + "." + S.LastName; break; case WebAssignUserName.First_Name_plus_Last_Name: StrUserName = S.FirstName + NewStudentIndex + "." + S.LastName; break; case WebAssignUserName.First_Name_Initial_plus_Middle_Initial_plus_Last_Name: StrUserName = S.FirstName.Substring(0, 1); if ((S.MiddleName != null) && (S.MiddleName != "")) { StrUserName += S.MiddleName.Substring(0, 1); } StrUserName += NewStudentIndex + "." + S.LastName; break; default: break; } NewStudentIndex++; } while (waUserNames.ContainsKey(StrUserName)); StrUserName = StripIllegalCharacters(StrUserName); if (waUserNames.ContainsKey(StrUserName)) { // use full name StrUserName = S.FirstName; if ((S.MiddleName != null) && (S.MiddleName != "")) { StrUserName += "." + S.MiddleName; } StrUserName += "." + S.LastName; StrUserName = StripIllegalCharacters(StrUserName); } if (waUserNames.ContainsKey(StrUserName)) { // ERROR msg += "Unable to calculate a unique user name for " + StrUserName + "'. Using full name."; } else { msg += "'" + StrUserName + "'."; waUserNames.Add(StrUserName, 1); } SendMessage(this, new Information(msg)); } else { waUserNames.Add(StrUserName, 1); } // Eliminate illegal character (-) from username and password string StrWebassignUserName = StripIllegalCharacters(StrUserName).ToLower(); string StrWebassignPassword = StripIllegalCharacters(StrUserPassword).ToLower(); sbCourse.Append(StrWebassignUserName + StrSEPERATOR_TYPE); // username sbCourse.Append(StrFullName.ToLower() + StrSEPERATOR_TYPE); // fullname //sbCourse.Append( StrWebassignPassword + StrSEPERATOR_TYPE); // password sbCourse.Append(S.Email.ToLower() + StrSEPERATOR_TYPE); // email sbCourse.Append(StripIllegalCharacters(S.SID).ToLower() + "\r\n"); // SID int intInstitutionHeader = 0; int intUserNameHeader = 0; int intPasswordHeader = 0; int intInstitutionUser = 0; int intUserNameUser = 0; int intPasswordUser = 0; int intSpacer = 0; string StrInstitutionHeader = "Institution"; string StrUserNameHeader = "Username"; string StrPasswordHeader = "Password"; string StrInstitution = WebAssignSettings.Institution; int intFillnameSpacer = 0; // Adjust the header/user spaces if (StrUserNameHeader.Length > StrUserName.Length) { intUserNameHeader = 0; intUserNameUser = StrUserNameHeader.Length - StrWebassignUserName.Length; } else { intUserNameHeader = StrWebassignUserName.Length - StrUserNameHeader.Length; intUserNameUser = 0; } if (StrInstitutionHeader.Length > StrInstitution.Length) { intInstitutionHeader = 0; intInstitutionUser = StrInstitutionHeader.Length - StrInstitution.Length; } else { intInstitutionHeader = StrInstitution.Length - StrInstitutionHeader.Length; intInstitutionUser = 0; } if (StrPasswordHeader.Length > StrUserPassword.Length) { intPasswordHeader = 0; intPasswordUser = StrPasswordHeader.Length - StrWebassignPassword.Length; } else { intPasswordHeader = StrWebassignPassword.Length - StrPasswordHeader.Length; intPasswordUser = 0; } intSpacer = 10 + StrInstitutionHeader.Length + intInstitutionHeader + StrUserNameHeader.Length + intUserNameHeader + StrPasswordHeader.Length + intPasswordHeader; string StrSpacer = new String('-', intSpacer); // For intLoop = 0 To intSpacer // StrSpacer = StrSpacer & "-" // Next if ((intSpacer - 3) > StrFullName.Length) { intFillnameSpacer = (intSpacer - StrFullName.Length) - 4; } else { intFillnameSpacer = 0; } sbStudent.Append(StrSpacer + "\r\n"); sbStudent.Append("| " + StrFullName + new String(' ', intFillnameSpacer) + " |" + "\r\n"); sbStudent.Append(StrSpacer + "\r\n"); sbStudent.Append("| " + StrUserNameHeader + new String(' ', intUserNameHeader) + " | " + StrInstitutionHeader + new String(' ', intInstitutionHeader) + " | " + StrPasswordHeader + new String(' ', intPasswordHeader) + " |" + "\r\n\r\n"); sbStudent.Append("| " + StrWebassignUserName.ToLower() + new String(' ', intUserNameUser) + " | " + StrInstitution + new String(' ', intInstitutionUser) + " | " + StrWebassignPassword.ToLower() + new String(' ', intPasswordUser) + " |" + "\r\n"); sbStudent.Append(StrSpacer + "\r\n\r\n\r\n"); } } String[] DiskNames = { C.DiskName(WebAssignSettings.Underscore) + ".txt", C.DiskName(WebAssignSettings.Underscore) + "_Students.txt" }; String[] FileContents = { sbCourse.ToString(), sbStudent.ToString() }; for (int i = 0; i < 1; i++) // 1 = only export the rooster list - modified on 2014-04-04 { FileInformation FE = new FileInformation("The file " + DiskNames[i] + " already exists.", WebAssignSettings.Directory, DiskNames[i]); DeleteFileError = false; // check to see if file exists SendMessage(this, new Information("Preparing " + DiskNames[i] + ".")); if (File.Exists(FE.OldFileNameandPath)) { SendMessage(this, new Information("File already exists.")); if (UserSettings.OverWriteAll) { try { SendMessage(this, new Information("Attempting to replace.")); File.Delete(FE.OldFileNameandPath); } catch { DeleteFileError = true; } } else { FileExistsMessage(this, FE); UserSettings.OverWriteAll = FE.OverWriteAll; if (FE.CancelALLExport) { SendMessage(this, new Information("Canceling WebAssign export.")); return; } if ((!FE.CancelExport) && (FE.OldFileNameandPath == FE.NewFileNameandPath)) { try { File.Delete(FE.OldFileNameandPath); } catch { DeleteFileError = true; } } } } if (FE.CancelExport) { SendMessage(this, new Information("User Canceled export for file.")); } else if (DeleteFileError) { SendMessage(this, new Information("Unable to delete file!")); } else { try { SendMessage(this, new Information("Writing file to disk.")); File.WriteAllText(FE.NewFileNameandPath, FileContents[i]); } catch (Exception Ex) { SendMessage(this, new Information("While trying to write " + FE.OldFileNameandPath + "An error occurred.\r\n" + Ex.Message)); } } } } } } catch (Exception Ex) { SendMessage(this, new Information("An unexpected error occurred - " + Ex.Message)); throw; } }
public void getFileList(DirectoryInfo di){ //set current directory currentDirectory = di; //get parent if(backTexture) parentDir = (di.Parent==null)?new DirectoryInformation(di,backTexture):new DirectoryInformation(di.Parent,backTexture); else parentDir = (di.Parent==null)?new DirectoryInformation(di):new DirectoryInformation(di.Parent); showDrives = di.Parent==null; //get drives string[] drvs = System.IO.Directory.GetLogicalDrives(); drives = new DirectoryInformation[drvs.Length]; for(int v=0;v<drvs.Length;v++){ drives[v]= (driveTexture==null)?new DirectoryInformation(new DirectoryInfo(drvs[v])):new DirectoryInformation(new DirectoryInfo(drvs[v]),driveTexture); } //get directories DirectoryInfo[] dia = di.GetDirectories(); directories = new DirectoryInformation[dia.Length]; for(int d=0;d<dia.Length;d++){ if(directoryTexture) directories[d] = new DirectoryInformation(dia[d],directoryTexture); else directories[d] = new DirectoryInformation(dia[d]); } //get files FileInfo[] fia = di.GetFiles(searchPattern); //FileInfo[] fia = searchDirectory(di,searchPattern); files = new FileInformation[fia.Length]; for(int f=0;f<fia.Length;f++){ if(fileTexture) files[f] = new FileInformation(fia[f],fileTexture); else files[f] = new FileInformation(fia[f]); } }
//Print Excel file Details public static void printExcelFileDetails(ClientContext clientContext) { List emplist = clientContext.Web.Lists.GetByTitle("UserDocuments"); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><RowLimit></RowLimit></View>"; ListItemCollection empcoll = emplist.GetItems(camlQuery); clientContext.Load(empcoll); clientContext.ExecuteQuery(); Microsoft.SharePoint.Client.File excelFile = empcoll[0].File; clientContext.Load(excelFile); clientContext.ExecuteQuery(); var filepath = empcoll[0].File.ServerRelativeUrl; var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, filepath); Console.WriteLine("file path :" + filepath); Console.WriteLine("file info :" + fileInfo); Console.WriteLine("file name :" + excelFile.Name); /***MyMyMy*****/ Microsoft.SharePoint.Client.File createfileinvs = empcoll[0].File; if (createfileinvs != null) { FileInformation fileInfor = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, createfileinvs.ServerRelativeUrl); var fileName = Path.Combine(@"D:\DharanendraAssessment13-oct-2018\SharePointCSOMAssessment\SharePointCSOMAssessment", (string)empcoll[0].File.Name); using (var fileStream = System.IO.File.Create(fileName)) { fileInfo.Stream.CopyTo(fileStream); } } /***MyMyMy*****/ /***************************************************************************************/ bool isError = true; string strErrorMsg = string.Empty; const string lstDocName = "Documents"; try { dataTable = new System.Data.DataTable("EmployeeExcelDataTable"); //List list = clientContext.Web.Lists.GetByTitle(lstDocName); //clientContext.Load(list.RootFolder); //clientContext.ExecuteQuery(); //string fileServerRelativeUrl = list.RootFolder.ServerRelativeUrl + "/" + fileName; //Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(fileServerRelativeUrl); ClientResult <System.IO.Stream> data = excelFile.OpenBinaryStream(); clientContext.Load(excelFile); clientContext.ExecuteQuery(); using (System.IO.MemoryStream mStream = new System.IO.MemoryStream()) { if (data != null) { data.Value.CopyTo(mStream); using (SpreadsheetDocument document = SpreadsheetDocument.Open(mStream, false)) { WorkbookPart workbookPart = document.WorkbookPart; IEnumerable <Sheet> sheets = document.WorkbookPart.Workbook.GetFirstChild <Sheets>().Elements <Sheet>(); string relationshipId = sheets.First().Id.Value; WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId); Worksheet workSheet = worksheetPart.Worksheet; SheetData sheetData = workSheet.GetFirstChild <SheetData>(); IEnumerable <Row> rows = sheetData.Descendants <Row>(); foreach (Cell cell in rows.ElementAt(0)) { string str = GetCellValue(clientContext, document, cell); dataTable.Columns.Add(str); } foreach (Row row in rows) { if (row != null) { DataRow dataRow = dataTable.NewRow(); for (int i = 0; i < row.Descendants <Cell>().Count(); i++) { dataRow[i] = GetCellValue(clientContext, document, row.Descendants <Cell>().ElementAt(i)); Console.WriteLine("Cell data :" + GetCellValue(clientContext, document, row.Descendants <Cell>().ElementAt(i))); } dataTable.Rows.Add(dataRow); } } dataTable.Rows.RemoveAt(0); } } } // UpdateSPList(clientContext, dataTable, fileName); isError = false; } catch (Exception e) { throw; } finally { if (isError) { //Logging } } /***************************************************************************************/ }
public void RemoveGetFileInfoCache() { GetFileInfoRet = NtStatus.MaximumNtStatus; GetFileInfoValue = new FileInformation(); }
public Upload(string documentId, FileInformation fileInformation, string uploadUrl) { DocumentId = documentId; FileInformation = fileInformation; UploadUrl = uploadUrl; }
private void ProcessFileList(IEnumerable <string> fileList, ref Dictionary <LoadOrdering, List <FileInformation> > sortedFiles, string archive = null) { foreach (string file in fileList) { var ext = Path.GetExtension(file).ToUpper() ?? String.Empty; FileInformation fileInformation = new FileInformation(Path.GetDirectoryName(file), Path.GetFileName(file), archive); switch (ext) { case ".LUA": sortedFiles[LoadOrdering.LUASCRIPT].Add(fileInformation); break; case ".LUASES": sortedFiles[LoadOrdering.LUASESSION].Add(fileInformation); break; case ".STATE": sortedFiles[LoadOrdering.STATE].Add(fileInformation); break; case ".CHT": sortedFiles[LoadOrdering.CHEAT].Add(fileInformation); break; case ".WCH": sortedFiles[LoadOrdering.WATCH].Add(fileInformation); break; case ".CDL": sortedFiles[LoadOrdering.CDLFILE].Add(fileInformation); break; default: if (MovieService.IsValidMovieExtension(ext)) { sortedFiles[LoadOrdering.MOVIEFILE].Add(fileInformation); } else if (MovieImport.IsValidMovieExtension(ext)) { sortedFiles[LoadOrdering.LEGACYMOVIEFILE].Add(fileInformation); } else if (knownROMExtensions.Contains(ext)) { if (String.IsNullOrEmpty(archive) || !nonArchive.Contains(ext)) { sortedFiles[LoadOrdering.ROM].Add(fileInformation); } } else { /* Because the existing behaviour for archives is to try loading * ROMs out of them, that is exactly what we are going to continue * to do at present. Ideally, the archive should be scanned and * relevant files should be extracted, but see the note below for * further details. */ int offset = 0; bool executable = false; var archiveHandler = new SevenZipSharpArchiveHandler(); if (String.IsNullOrEmpty(archive) && archiveHandler.CheckSignature(file, out offset, out executable)) { sortedFiles[LoadOrdering.ROM].Add(fileInformation); } /* * This is where handling archives would go. * Right now, that's going to be a HUGE hassle, because of the problem with * saving things into the archive (no) and with everything requiring filenames * and not streams (also no), so for the purposes of making drag/drop more robust, * I am not building this out just yet. * -- Adam Michaud (Invariel) * * int offset = 0; * bool executable = false; * var archiveHandler = new SevenZipSharpArchiveHandler(); * * // Not going to process nested archives at the moment. * if (String.IsNullOrEmpty (archive) && archiveHandler.CheckSignature(file, out offset, out executable)) * { * List<string> fileNames = new List<string>(); * var openedArchive = archiveHandler.Construct (file); * * foreach (BizHawk.Common.HawkFileArchiveItem item in openedArchive.Scan ()) * fileNames.Add(item.Name); * * ProcessFileList(fileNames.ToArray(), ref sortedFiles, file); * * openedArchive.Dispose(); * } * archiveHandler.Dispose(); */ } break; } } }
private async Task<FileInformation> GetMailFile(FileInfo currFile) { var result = await TaskEx.RunEx<FileInformation>(async () => { FileInformation fileinfo = new FileInformation() { Id = Guid.NewGuid().ToString("N"), FileName = currFile.Name, Extension = _filter.getExtension(currFile.Name), NameOnDisk = currFile.FullName, FileType = FileType.Email, FileSize = currFile.Length, LastAccessTime = currFile.LastAccessTime, LastWriteTime = currFile.LastWriteTime, CreationTime = currFile.CreationTime, FileOrigin = FileOrigin.Disk, FileStatus = FileStatus.Allocated, MD5Hash = await GetHash(currFile.FullName, HashType.MD5), IsPhysical = true }; return fileinfo; }); return result; }
public async Task <GetPreviewNewsfeedQueryResult> HandleAsync(GetNewsfeedQuery query) { query.AssertNotNull("query"); var requestingUserId = await this.requesterSecurity.TryAuthenticateAsync(query.Requester); var now = this.timestampCreator.Now(); var postsResult = await this.getPreviewNewsfeedDbStatement.ExecuteAsync( requestingUserId, query.CreatorId, query.ChannelIds, now, query.Origin ?? now, query.SearchForwards, query.StartIndex, query.Count); var posts = postsResult.Posts; var expiry = this.getAccessSignatureExpiryInformation.Execute(now); var results = new List <GetPreviewNewsfeedQueryResult.PreviewPost>(); foreach (var post in posts) { FileInformation profileImage = null; if (post.ProfileImageFileId != null) { profileImage = await this.fileInformationAggregator.GetFileInformationAsync( null, post.ProfileImageFileId, FilePurposes.ProfileImage); } FileInformation image = null; BlobSharedAccessInformation imageAccessInformation = null; if (post.ImageId != null) { image = await this.fileInformationAggregator.GetFileInformationAsync( post.ChannelId, post.ImageId, FilePurposes.PostImage); var imageType = post.IsFreePost ? FileManagement.Shared.Constants.PostFeedImageThumbnailName : FileManagement.Shared.Constants.PostPreviewImageThumbnailName; imageAccessInformation = await this.blobService.GetBlobSharedAccessInformationForReadingAsync( image.ContainerName, image.FileId.Value.EncodeGuid() + "/" + imageType, expiry.Public); } RenderSize imageRenderSize = null; if (post.ImageRenderWidth.HasValue && post.ImageRenderHeight.HasValue) { imageRenderSize = new RenderSize(post.ImageRenderWidth.Value, post.ImageRenderHeight.Value); } var completePost = new GetPreviewNewsfeedQueryResult.PreviewPost( post.CreatorId, new GetPreviewNewsfeedQueryResult.PreviewPostCreator(new Username(post.Username), profileImage), post.PostId, post.BlogId, new GetPreviewNewsfeedQueryResult.PreviewPostBlog(new BlogName(post.BlogName), null, null), post.ChannelId, new GetPreviewNewsfeedQueryResult.PreviewPostChannel(new ChannelName(post.ChannelName)), post.PreviewText, image, image == null ? null : new FileSourceInformation(post.ImageName, post.ImageExtension, this.mimeTypeMap.GetMimeType(post.ImageExtension), post.ImageSize ?? 0, imageRenderSize), imageAccessInformation, post.PreviewWordCount, post.WordCount, post.ImageCount, post.FileCount, post.VideoCount, post.LiveDate, post.LikesCount, post.CommentsCount, post.HasLikedPost, post.IsFreePost); results.Add(completePost); } return(new GetPreviewNewsfeedQueryResult(results)); }
private async Task<FileInformation> GetImageFile(FileInfo currFile) { var result = await TaskEx.Run<FileInformation>(() => { FileInformation fileinfo = new FileInformation() { FileName = currFile.Name, Extension = _filter.getExtension(currFile.Name), NameOnDisk = currFile.FullName, FileType = FileType.Image, FileSize = currFile.Length, LastAccessTime = currFile.LastAccessTime, LastWriteTime = currFile.LastWriteTime, CreationTime = currFile.CreationTime, FileOrigin = FileOrigin.Disk, FileStatus = FileStatus.Allocated, IsPhysical = true }; return fileinfo; }); return result; }
public GUIListItem(string aLabel, string aLabel2, string aPath, bool aIsFolder, FileInformation aFileInformation) { if (String.IsNullOrEmpty(aLabel)) { return; } _label = aLabel; _label2 = aLabel2; _folder = aPath; _isFolder = aIsFolder; _fileInfo = aFileInformation; }
private void ProcessFileList(IEnumerable <string> fileList, ref Dictionary <LoadOrdering, List <FileInformation> > sortedFiles, string archive = null) { foreach (string file in fileList) { var ext = Path.GetExtension(file)?.ToUpperInvariant() ?? ""; FileInformation fileInformation = new FileInformation(Path.GetDirectoryName(file), Path.GetFileName(file), archive); switch (ext) { case ".LUA": sortedFiles[LoadOrdering.LuaScript].Add(fileInformation); break; case ".LUASES": sortedFiles[LoadOrdering.LuaSession].Add(fileInformation); break; case ".STATE": sortedFiles[LoadOrdering.State].Add(fileInformation); break; case ".CHT": sortedFiles[LoadOrdering.Cheat].Add(fileInformation); break; case ".WCH": sortedFiles[LoadOrdering.Watch].Add(fileInformation); break; case ".CDL": sortedFiles[LoadOrdering.CdFile].Add(fileInformation); break; default: if (MovieService.IsValidMovieExtension(ext)) { sortedFiles[LoadOrdering.MovieFile].Add(fileInformation); } else if (MovieImport.IsValidMovieExtension(ext)) { sortedFiles[LoadOrdering.LegacyMovieFile].Add(fileInformation); } else if (RomLoader.KnownRomExtensions.Contains(ext)) { if (string.IsNullOrEmpty(archive) || !_nonArchive.Contains(ext)) { sortedFiles[LoadOrdering.Rom].Add(fileInformation); } } else { /* Because the existing behaviour for archives is to try loading * ROMs out of them, that is exactly what we are going to continue * to do at present. Ideally, the archive should be scanned and * relevant files should be extracted, but see the note below for * further details. */ var dearchivalMethod = SharpCompressDearchivalMethod.Instance; if (string.IsNullOrEmpty(archive) && dearchivalMethod.CheckSignature(file, out _, out _)) { sortedFiles[LoadOrdering.Rom].Add(fileInformation); } else { // This is hack is to ensure that unrecognized files are treated like ROMs sortedFiles[LoadOrdering.Rom].Add(fileInformation); } #if false /* * This is where handling archives would go. * Right now, that's going to be a HUGE hassle, because of the problem with * saving things into the archive (no) and with everything requiring filenames * and not streams (also no), so for the purposes of making drag/drop more robust, * I am not building this out just yet. * -- Adam Michaud (Invariel) */ // Not going to process nested archives at the moment. if (string.IsNullOrEmpty(archive) && archiveHandler.CheckSignature(file, out _, out _)) { using var openedArchive = archiveHandler.Construct(file); ProcessFileList(openedArchive.Scan().Select(item => item.Name), ref sortedFiles, file); } archiveHandler.Dispose(); #endif } break; } } }
public abstract NtStatus GetFileInfo(string fileName, out FileInformation fileInfo, DokanFileInfo info);
private void MD5Scan(bool bAuto) { ClearMemory(); double percentage = 0, ProcessedFileCount = 0; int TempCount = 5, t1 = 1, t2 = 0; FileInformation fileInfo = new FileInformation(); Console.WriteLine("----MD5 SCAN----"); Console.WriteLine("MD5 scanning is about to start."); Console.WriteLine("This operation may take up to a long time."); Console.WriteLine("Press enter to continue."); Console.WriteLine("Starting scan....please wait!"); Console.WriteLine("Calculating number of files..."); foreach (string strPath in DirectoryList) { fStats.FileCount += Directory.GetFiles(strPath).GetLongLength(0); } Console.WriteLine("Finished counting files, there is {0} files to be calculated.", fStats.FileCount); Console.WriteLine("Performing MD5 calculations..."); foreach (string strPath in DirectoryList) { foreach (string strItem in Directory.GetFiles(strPath)) { try { percentage = (ProcessedFileCount / fStats.FileCount) * 100; TempCount = Percent(percentage, out t2); if (t1 != t2 && TempCount > 0) { Console.WriteLine("Processed {0}% of the files...", TempCount); t1 = t2; } fileInfo = new FileInformation(); fileInfo.Filepath = strItem; fileInfo.FileSize = File.ReadAllBytes(strItem).LongLength; fileInfo.MD5 = GetMD5HashFromFile(strItem); fileInfo.bDuplicate = CheckIfMD5Exists(fileInfo.MD5); if (fileInfo.bDuplicate) { fStats.TotalDuplicates++; fStats.FileDuplicateRemovalSize += fileInfo.FileSize; fDelete.Add(fileInfo); } fStats.TotalSize += fileInfo.FileSize; fInfo.Add(fileInfo); ProcessedFileCount++; } catch (Exception) { } } } Console.WriteLine("Calculated MD5 checksums, ready to perform next step..."); if (!bAuto) { Console.WriteLine("Task completed. Press enter to continue."); Console.ReadLine(); MainMenu(); } }
/// <remarks> /// Support for pass-through Information Levels must be enabled. /// </remarks> public void SetFileInformation(FileInformation information) { InformationBytes = information.GetBytes(); }
private FileInformation GetSaveFileNameAndEncoding() { FileInformation returnValue = new FileInformation(); // Изначально устанавливаем путь в Мои документы dialogSave.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Очищаем предыдущее имя файла dialogSave.FileName = string.Empty; // Если есть уже открытый файл if (fileName != string.Empty) { // Если расширение файла - txt, то имя файла без расширения // Если расширение файла другое, то имя файла с расширением if (Path.GetExtension(fileName).ToLower() == ".txt") { dialogSave.FileName = Path.GetFileNameWithoutExtension(fileName); } else { dialogSave.FileName = Path.GetFileName(fileName); } // Проверим, существует ли папка с файлом string fileFolder = Path.GetDirectoryName(fileName); if (Directory.Exists(fileFolder)) { dialogSave.InitialDirectory = fileFolder; } } if (dialogSave.ShowDialog() == DialogResult.OK) { // Пользователь выбрал файл, начинаем спрашивать у него кодировку returnValue.fileName = dialogSave.FileName; // Спрашиваем кодировку if (formEncoding == null) formEncoding = new FormEncoding(); returnValue.fileEncoding = formEncoding.SelectEncoding(fileEncoding); } return returnValue; }
public LoadFileWrapper(IDisplayBinding binding, FileInformation fileInfo) { this.fileInfo = fileInfo; this.binding = binding; }
private void buttonOK_Click(object sender, EventArgs e) { _result = null; using (new WaitCursor(this, WaitCursorOption.ShortSleep)) { var cultures = getCultures(); var baseFolderPath = baseFolderTextEdit.Text.Trim(); var baseFileName = baseFileNameTextEdit.Text.Trim(); var extension = @"." + extensionComboBoxEdit.Text.Trim('.'); var created = 0; using (new BackgroundWorkerLongProgressGui( delegate(object snd, DoWorkEventArgs args) { try { var bw = (BackgroundWorker)snd; // -- // First pass, add all in-memory to check for same file group. var fg = new FileGroup(_project); if (cultures != null) { foreach (var culture in cultures) { var fileName = _project.IsNeutralLanguage(culture) ? baseFileName + extension : generateFileName(fg, culture); fg.Add(new FileInformation(fg) { File = new ZlpFileInfo(fileName) }); } // Look for same entries. if (_project.FileGroups.HasFileGroupWithChecksum( fg.GetChecksum(_project))) { throw new MessageBoxException( this, Resources.SR_ProjectFilesUserControl_AddResourceFilesWithDialog_ExistsInTheProject, MessageBoxIcon.Information); } else { // -- // Second pass, add all existing. fg = new FileGroup(_project); foreach (var culture in cultures) { if (bw.CancellationPending) { throw new OperationCanceledException(); } var fileName = _project.IsNeutralLanguage(culture) ? baseFileName + extension : generateFileName(fg, culture); FileInformation ffi; if (_project.IsNeutralLanguage(culture)) { ffi = new FileInformation(fg) { File = new ZlpFileInfo(ZlpPathHelper.Combine(baseFolderPath, fileName)) }; fg.Add(ffi); } else { ffi = fg.CreateAndAddNewFile( baseFolderPath, fileName, culture.Name); } // Must create real file. ZlpIOHelper.WriteAllText(ffi.File.FullName, Resources.SR_EmptyResourceFile); created++; } } } if (_projectFolder != null) { fg.ProjectFolder = _projectFolder; } _project.FileGroups.Add(fg); _project.MarkAsModified(); _result = fg; } catch (OperationCanceledException) { // Ignore. } }, Resources.SR_CreateNewFilesForm_Creating, BackgroundWorkerLongProgressGui.CancellationMode.Cancelable, this)) { } // -- XtraMessageBox.Show( this, string.Format( Resources.SR_CreateNewFilesForm_Finished03, created), @"Zeta Resource Editor", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public NtStatus FindStreams(string fileName, out IList <FileInformation> streams, DokanFileInfo info) { streams = new FileInformation[0]; return(DokanResult.NotImplemented); }
public CrunchGroup(string outputPath, string encodingOutputName) { Output = new FileInformation() { Path = outputPath, EncodingName = encodingOutputName }; m_sourcePaths = new List<FileInformation>(); }
private FileInformation GetOpenFileNameAndEncoding() { FileInformation returnValue = new FileInformation(); // Изначально устанавливаем путь в Мои документы dialogOpen.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Если есть уже открытый файл, то установим его папку if (fileName != string.Empty) { // Проверим, существует ли эта папка? string fileFolder = Path.GetDirectoryName(fileName); if (Directory.Exists(fileFolder)) { dialogOpen.InitialDirectory = fileFolder; } } // Очищаем предыдущее имя файла dialogOpen.FileName = string.Empty; if (dialogOpen.ShowDialog() == DialogResult.OK) { // Пользователь выбрал файл, начинаем спрашивать у него кодировку returnValue.fileName = dialogOpen.FileName; // Попытаться определить кодировку файла по первым 2 или 3 байтам Encoding fileEncoding = CheckFileEncoding(returnValue.fileName); // Спрашиваем кодировку if (formEncoding == null) formEncoding = new FormEncoding(); returnValue.fileEncoding = formEncoding.SelectEncoding(fileEncoding); } return returnValue; }
public ValueTask <IEnumerable <IFileIssue> > CheckForIssues(FileInformation file, IFileBaseContext fileBaseContext, IPhotoDirectoryDataContext dataContext) { return(new ValueTask <IEnumerable <IFileIssue> >(CheckForIssues(file, fileBaseContext))); }
/// <summary> /// Convierte un paquete de bytes en las propiedades del mensaje /// </summary> /// <param name="messagePack">El paquete de bytes</param> public override void unPack(byte[] messagePack) { FileList = new FileInformationList(); int listSize = BitConverter.ToInt32(messagePack, 0); int i = 4; for (int n = 0; n < listSize; n++) { FileInformation fileInformation = new FileInformation(); byte[] id = new byte[16]; Array.Copy(messagePack, i, id, 0, 16); fileInformation.Id = new Guid(id); i += 16; fileInformation.Size = BitConverter.ToInt64(messagePack, i); i += 8; int nameSize = BitConverter.ToInt32(messagePack, i); i += 4; fileInformation.Name = Encoding.Unicode.GetString(messagePack, i, nameSize); i += nameSize; FileList.add(fileInformation); } }
private void OpenLastTrackList() { var filePaths = SQLiteDataAccess.LoadLastTrackList(); Files = FileInformation.CreateFilesList(filePaths); }
protected void searchFileList(DirectoryInfo di,bool hasTexture) { FileInfo[] fia = di.GetFiles((searchBarString.IndexOf("*") >= 0)?searchBarString:"*"+searchBarString+"*",(searchRecursively)?SearchOption.AllDirectories:SearchOption.TopDirectoryOnly); files = new FileInformation[fia.Length]; for(int f=0;f<fia.Length;f++){ if(hasTexture) files[f] = new FileInformation(fia[f],fileTexture); else files[f] = new FileInformation(fia[f]); } isSearching = false; }
public void DeleteSelectedTrack(FileInformation file) { Files.Remove(file); OnPropertyChanged(nameof(Files)); }
public void RemoveGetFileInfoCache() { GetFileInfoRet = DokanError.Undefined; GetFileInfoValue = new FileInformation(); }
public static void MPRSimulation(FogPost edge, TuplePost tuple, string policy, int CommunicationType, int Service, List <string> DataCenter, string gateway, string cooperation, string edgeType) { Random rnd = new Random(); Stopwatch watch = new Stopwatch(); var result = new Results(); edgeResultList = new List <Results>(); edgeList = new List <FogDevice>(); tupleList = new List <Models.Tuple>(); PowerUtility.FillNumRange(); string JsonReturn, path; #region DataSet reading if (edgeType == "0") { #region Memory Homogenious path = (new FileInfo(Path.Combine(FileInformation.GetDirectory(), "H**o\\JsonFog.txt"))).ToString(); JsonReturn = SimJson.ReadJsonFile(path); edgeList = JsonConvert.DeserializeObject <List <FogDevice> >(JsonReturn); EdgeSize = edgeList.Count; #endregion #region Tuple homogenious path = (new FileInfo(Path.Combine(FileInformation.GetDirectory(), "H**o\\JsonTuple.txt"))).ToString(); JsonReturn = SimJson.ReadJsonFile(path); tupleList = JsonConvert.DeserializeObject <List <Models.Tuple> >(JsonReturn); #endregion Tuple } else { #region Memory Hetrogenous path = (new FileInfo(Path.Combine(FileInformation.GetDirectory(), "Hetro\\JsonFog.txt"))).ToString(); JsonReturn = SimJson.ReadJsonFile(path); edgeList = JsonConvert.DeserializeObject <List <FogDevice> >(JsonReturn); EdgeSize = edgeList.Count; #endregion #region Tuple Hetrogenious path = (new FileInfo(Path.Combine(FileInformation.GetDirectory(), "Hetro\\JsonTuple.txt"))).ToString(); JsonReturn = SimJson.ReadJsonFile(path); tupleList = JsonConvert.DeserializeObject <List <Models.Tuple> >(JsonReturn); #endregion Tuple } #region create fog for Edge-fog cloud if (CommunicationType == 1) { int fCount = Convert.ToInt32(EdgeSize / 2); for (int i = 0; i < fCount; i++) { bool[] bit = { true }; var b = rnd.Next(bit.Length); int[] randomRam = { 512, 1024, 2048, 3072, 3584, 4096 }; // var randomRamIndex = rnd.Next(randomRam.Length); var index = rnd.Next(randomRam.Length); int[] randomMips = { 2000, 4000, 8000, 12000, 18000, 20000 }; var randomMipsIndex = rnd.Next(randomMips.Length); int[] randomPe = { 1, 1, 2, 2, 3, 4 }; var randomPeIndex = rnd.Next(randomPe.Length); int[] randomSize = { 4000, 5000, 7000, 10000, 12000, 15000 }; var randomSizeIndex = rnd.Next(randomSize.Length); int[] randomDownBW = { 400, 500, 700, 1000, 1200, 1500 }; var randomDownBWIndex = rnd.Next(randomDownBW.Length); int[] randomUpBW = { 500, 700, 1000, 1200, 1500, 2000 }; var randomUpBWIndex = rnd.Next(randomUpBW.Length); int[] randomStorage = { 2500, 4500, 5000, 7000, 10000, 12000 }; var randomStorageIndex = rnd.Next(randomStorage.Length); Array NodeTypevalues = Enum.GetValues(typeof(EnumNodeType)); EnumNodeType randomDataType = (EnumNodeType)NodeTypevalues.GetValue(rnd.Next(NodeTypevalues.Length)); fogServers.Add(new FogDevice( Guid.NewGuid(), 1, randomMips[index], randomPe[index], randomRam[index], randomUpBW[index], randomDownBW[index], randomSize[index], randomStorage[index], "fog" + "-" + i, randomDataType.ToString(), new CloudletScheduler(), GeoDistance.RandomGeoLocation(rnd), bit[b], 0, PowerUtility.SetIdlePower()) ); } } #endregion #endregion SmartThreadPool s = new SmartThreadPool(); s.MaxThreads = 1000; s.MinThreads = 1000; List <Task> myTaskList = new List <Task>(); if (policy == "1") { //FCFS #region P1 FCFS s = new SmartThreadPool(); watch.Start(); foreach (var item in tupleList) { s.QueueWorkItem(o => FogUtility.EdgeSim(item, edgeList, CommunicationType), new object()); } watch.Stop(); try { s.WaitForIdle(); s.Shutdown(); } catch { }; #endregion } else if (policy == "2") { #region P2 SJF var localtupleList = tupleList.OrderBy(x => x.MIPS).ToList(); s = new SmartThreadPool(); watch.Start(); foreach (var item in localtupleList) { s.QueueWorkItem(o => FogUtility.EdgeSim(item, edgeList, CommunicationType), new object()); } watch.Stop(); try { s.WaitForIdle(); s.Shutdown(); } catch { }; #endregion } else if (policy == "3") { #region P3 LJF var localtupleList = tupleList.OrderByDescending(x => x.MIPS).ToList(); s = new SmartThreadPool(); watch.Start(); foreach (var item in localtupleList) { s.QueueWorkItem(o => FogUtility.EdgeSim(item, edgeList, CommunicationType), new object()); } watch.Stop(); try { s.WaitForIdle(); s.Shutdown(); } catch { }; #endregion } else { #region random try { var split = LinqExtensions.Split(tupleList, 16).ToList(); watch.Start(); s = new SmartThreadPool(); for (int j = 0; j < split.Count(); j++) { foreach (var item in split[j]) { s.QueueWorkItem(o => FogUtility.EdgeSim(item, edgeList, CommunicationType), new object()); } } try { s.WaitForIdle(); s.Shutdown(); } catch { }; } catch (Exception ex) { throw ex; } #endregion } watch.Stop(); if (policy == "4") { if (edgeResultList != null) { Excel.CreateExcelSheetEdgeFog(edgeResultList, FogTimings.ToList(), TupleTimings.ToList(), DropedtupleList.ToList()); } } else { Excel.CreateExcelSheetEdgeFog(edgeResultList, FogTimings.ToList(), TupleTimings.ToList(), DropedtupleList.ToList()); if (CommunicationType == 1) { Excel.CreateExcelSheetForFog(FogSimulator.resultList, FogSimulator.FogTimings.ToList(), FogSimulator.TupleTimings.ToList()); } } }
public void AddResult(FileInformation file, string host) { LocalAddResult(file, host); }
public static string Log(this FileInformation fileInfo) => $"{nameof(FileInformation)} {{{fileInfo.FileName}, [{fileInfo.Attributes}], {fileInfo.CreationTime?.ToString() ?? "<null>"}, {fileInfo.LastWriteTime?.ToString() ?? "<null>"}, {fileInfo.LastAccessTime?.ToString() ?? "<null>"}, {fileInfo.Length}}}";
public int GetFileInformation(string sPath, FileInformation FI, DokanFileInfo DFI) { string sFileInfo; sPath = sPath.Replace("\\", "/"); FI.Attributes = System.IO.FileAttributes.Directory; FI.LastAccessTime = DateTime.Now; FI.LastWriteTime = DateTime.Now; FI.CreationTime = DateTime.Now; FI.Length = 0; try { sFileInfo = AFC.GetFileInfo(sPath); } catch (Exception) { return 0; } string[] sFileInfoParts = sFileInfo.Split(new char[] { '\x0' }); string sFileType = null; string sFileLength = null; for (int i = 0; i < sFileInfoParts.Length; i++) { if (sFileInfoParts[i] == "st_size" && i < (sFileInfoParts.Length - 1)) sFileLength = sFileInfoParts[i + 1]; else if (sFileInfoParts[i] == "st_ifmt" && i < (sFileInfoParts.Length - 1)) sFileType = sFileInfoParts[i + 1]; } FI.LastAccessTime = DateTime.Now; FI.LastWriteTime = DateTime.Now; FI.CreationTime = DateTime.Now; if (sFileLength != null) FI.Length = long.Parse(sFileLength); switch (sFileType) { case "S_IFLNK": case "S_IFDIR": FI.Attributes = FileAttributes.Directory; break; case "S_IFREG": FI.Attributes = FileAttributes.Normal; break; default: FI.Attributes = FileAttributes.Normal; break; } return 0; }
} //选择主题 public MainViewModel() { LanguageList = new List <string>(); ThemeList = new List <string>(); FontSizeList = new List <int>(); FontList = new List <string>(); Init(Application.StartupPath + @"\Configuration\Configuration.xml"); SelectedFont = "Consolas"; SelectedLanguage = "Python"; SelectedFontSize = 12; SelectedTheme = "Dark"; InputFolderCommand = new Command(() => { FolderBrowserDialog openFileDialog = new FolderBrowserDialog(); //选择文件夹 if (openFileDialog.ShowDialog() == DialogResult.OK) //注意,此处一定要手动引入System.Window.Forms空间,否则你如果使用默认的DialogResult会发现没有OK属性 { InputFolderPath = openFileDialog.SelectedPath; List <FileInformation> list = new List <FileInformation>(); FileInformation temp; //遍历文件夹 DirectoryInfo theFolder = new DirectoryInfo(InputFolderPath); FileInfo[] thefileInfo = theFolder.GetFiles("*" + FilenameExtensionDic[SelectedLanguage], SearchOption.TopDirectoryOnly); foreach (FileInfo NextFile in thefileInfo) //遍历文件 { temp = new FileInformation { Selected = true, FileName = NextFile.Name, EditTime = NextFile.LastWriteTime.ToString(), Size = NextFile.Length.ToString(), FullPath = NextFile.DirectoryName }; list.Add(temp); } // 暂时不包含子文件夹 //遍历子文件夹 DirectoryInfo[] dirInfo = theFolder.GetDirectories(); foreach (DirectoryInfo NextFolder in dirInfo) { //list.Add(NextFolder.ToString()); FileInfo[] fileInfo = NextFolder.GetFiles("*.py", SearchOption.AllDirectories); foreach (FileInfo NextFile in fileInfo) //遍历文件 { temp = new FileInformation { Selected = true, FileName = NextFile.Name, EditTime = NextFile.LastWriteTime.ToString(), Size = NextFile.Length.ToString(), FullPath = NextFile.DirectoryName }; list.Add(temp); } } FileList = list; } }, () => { return(true); }); OutputFolderCommand = new Command(() => { FolderBrowserDialog openFileDialog = new FolderBrowserDialog(); //选择文件夹 if (openFileDialog.ShowDialog() == DialogResult.OK) { OutputFolderPath = openFileDialog.SelectedPath; } }, () => { return(true); }); OpenInputFolderCommand = new Command(() => { ShellExecute(IntPtr.Zero, "open", InputFolderPath, "", "", 4); }, () => { return(true); }); OpenOutputFolderCommand = new Command(() => { ShellExecute(IntPtr.Zero, "open", OutputFolderPath, "", "", 4); }, () => { return(true); }); GenerateCommand = new Command(() => { ProgressWindow progressWindow = new ProgressWindow(SelectedLanguage, SelectedFont, SelectedFontSize.ToString(), SelectedTheme, OutputFolderPath, FileList); progressWindow.Show(); }, () => { return(true); }); SelectThemeCommand = new Command(() => { ThemeImage = "/Themes/" + SelectedLanguage + "_" + SelectedTheme + ".PNG"; }, () => { return(true); }); }
protected void searchFileList(DirectoryInfo di,bool hasTexture){ //(searchBarString.IndexOf("*") >= 0)?searchBarString:"*"+searchBarString+"*"; //this allows for more intuitive searching for strings in file names FileInfo[] fia = di.GetFiles((searchBarString.IndexOf("*") >= 0)?searchBarString:"*"+searchBarString+"*",(searchRecursively)?SearchOption.AllDirectories:SearchOption.TopDirectoryOnly); files = new FileInformation[fia.Length]; for(int f=0;f<fia.Length;f++){ if(hasTexture) files[f] = new FileInformation(fia[f],fileTexture); else files[f] = new FileInformation(fia[f]); } #if thread #else isSearching = false; #endif }
private static void ProcessUserAndTemplateChange(FileInformation<string> fileInfo, VisualDiffOutput output) { string[] newlines = Common.Utility.StandardizeLineBreaks( fileInfo.NewGenFile.GetContents(), Common.Utility.LineBreaks.Unix) .Split('\n'); ProcessSingleChange(fileInfo, output, newlines, ChangeType.Template); newlines = Common.Utility.StandardizeLineBreaks( fileInfo.UserFile.GetContents(), Common.Utility.LineBreaks.Unix) .Split('\n'); VisualDiffOutput secondOutput = new VisualDiffOutput(); ProcessSingleChange(fileInfo, secondOutput, newlines, ChangeType.User); output.MergeOutput(secondOutput, ChangeType.Template, ChangeType.User); }