private void pathTextBox_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Enter) { return; } string enteredPath = pathTextBox.Text; eFileType fileType = FileManagerUtils.GetCurrentPathType(enteredPath); if (fileType == eFileType.Folder) { m_currentPath = enteredPath; fillDataGridView(Directory.GetFileSystemEntries(enteredPath, "*", SearchOption.TopDirectoryOnly)); } else if (fileType == eFileType.File) { System.Diagnostics.Process.Start(enteredPath); } else // TODO web site should work also from url bar. { MessageBox.Show("Windows can't find '" + enteredPath + "'. Check the spelling and try again.", "File Explorer", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
// Das hier ist ein Konstruktor (muss genauso heissen wie die Klasse)! public MusicCollection(string Artist, string Album, int Year, int NumTracks, eFileType FileType) { if (Artist == null || Artist.Length == 0) { throw new Exception("No artist name!"); } if (Album == null || Album.Length == 0) { throw new Exception("No album name!"); } if (Year < 1900 || Year > 2017) { throw new Exception("Invalid release year!"); } if (NumTracks < 1 || NumTracks > 1000) { throw new Exception("Invalid number of tracks!"); } my_ArtistName = Artist; my_AlbumTitle = Album; my_ReleaseYear = Year; my_NumOfTracks = NumTracks; my_FileType = FileType; }
//------------------------------------------------ private IEnumerator loadResource(string name, string path, eFileType type) { WWW www = new WWW(path); yield return www; switch (type) { case eFileType.eFile_Mark: { _tempMark = www.texture; break; } case eFileType.eFile_Wally: { _tempWally = www.texture; break; } default: { break; } } www.Dispose(); www = null; _loadCount--; //load if (_loadCount == 0) { _isProcessing = false; _wallyMgr.newWally(ref _tempMark, ref _tempWally); } }
private eFileType GetFileType() { eFileType fType = eFileType.Unknown; if (afpFile != null && afpFile.Fields.Any()) { // If there are pages, it's a document if (afpFile.Fields.OfType <BPG>().Any()) { fType = eFileType.Document; } else { // If it's a page segment, check for images or fonts Type f1 = afpFile.Fields[0].GetType(); Type f2 = afpFile.Fields[1].GetType(); if (f1 == typeof(BPS) && f2 == typeof(BIM)) { fType = eFileType.IOCAImage; } else if (f1 == typeof(BPS) && f2 == typeof(BII)) { fType = eFileType.IMImage; } else if (f1 == typeof(BFN)) { fType = eFileType.Font; } } } return(fType); }
/// <summary> /// The user must specify the file name, “Canadacities”, /// and then determine the file type or extension to be JSON, XML, or CSV. /// </summary> /// <param name="filePath"></param> public Statistics(string filePath) { // If filepath exists if (File.Exists(filePath)) { // set file path FilePath = filePath; // get file extension and set it switch (filePath.Split('.')[2].ToUpper()) { case "CSV": FileType = eFileType.CSV; break; case "XML": FileType = eFileType.XML; break; case "JSON": FileType = eFileType.JSON; break; } // call the DataModeler parse file and store the reusting dictionary in the CityCatalogue dictionary DataModeler modeler = new DataModeler(); CityCatalogue = modeler.ParseFile(FilePath, FileType); } // else throw exception else { throw new FileNotFoundException("The file " + filePath + " Could not be found"); } }
public WaveFileWriter(FileStream stream, eFileType type) { Type = type; switch (Type) { case eFileType.WAV: // Fill in the appropriate members of the header WavHeader = new WaveHeader(); WavHeader.sound.dataSize = int.MaxValue; WavHeader.chunkSize = WavHeader.formatTag.Length + WavHeader.fmt.formatTag.Length + WavHeader.fmt.formatSize + sizeof(int) + WavHeader.sound.dataTag.Length + WavHeader.sound.dataSize + sizeof(int); // Open the destination .wav file Writer = new BinaryWriter(stream); // Write out the header WavHeader.Write(Writer); DataFormat = ByteUtil.eSampleFormat.Direct16BitIQFixedPointLE; break; case eFileType.RawIQ: Writer = new BinaryWriter(stream); DataFormat = ByteUtil.eSampleFormat.Direct16BitIQFixedPointLE; break; case eFileType.CFile: Writer = new BinaryWriter(stream); DataFormat = ByteUtil.eSampleFormat.Direct32BitIQFloat64k; break; } }
public eFileType DetermineFolderStateType(string source_path_filename) { eFileType result = eFileType.eUnknown; mlogger.TraceEvent(LogLevels.Verbose, 33027, "Determining state of {0}", source_path_filename); bool isdir = Directory.Exists(source_path_filename); bool isfile = File.Exists(source_path_filename); if (!isdir && !isfile) // folder is not there or no permissions { mlogger.TraceEvent(LogLevels.Warning, 33028, "Cannot access {0}", source_path_filename); return(result); } if (isdir) { mlogger.TraceEvent(LogLevels.Info, 33029, "Folder found"); result = eFileType.eFolder; } else { System.IO.FileInfo fi = null; fi = new System.IO.FileInfo(source_path_filename); if (//(fi.Attributes & FileAttributes.Compressed) == FileAttributes.Compressed || fi.Extension.ToLower().Equals(".zip") fi.Extension.ToLower().Equals(".zip") | fi.Extension.ToLower().Equals(".zipx") | fi.Extension.ToLower().Equals(".7z")) { result = eFileType.eZip; mlogger.TraceEvent(LogLevels.Info, 33030, "Compressed archive found"); // dev note: System.IO.Compression.DeflateStream does not provide for zipped folders, only zipped single files (the lame losers!), so need to find a full implementation of zip/unzip and add it here } } return(result); }
public static bool HasFile(eFileType fileType, string fileName, bool logExceptions = true) { if (mStorage == null) { mStorage = new I2CustomPersistentStorage(); } return(mStorage.HasFile(fileType, fileName, logExceptions)); }
private static bool TryGetFileType(string fileName, out eFileType fileType) { if (FileTypes.TryGetValue(Path.GetExtension(fileName), out fileType) == true) { return(true); } NotValidFileType.Invoke(null, new ErrorEventArgs(new NotSupportedException())); return(false); }
private void btnBrowse_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog() { InitialDirectory = opts.LastDirectory, Filter = "AFP Files (*.afp)|*.afp|All Files|*.*" }; DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { try { Cursor = Cursors.WaitCursor; // Store the last used options FileInfo fInfo = new FileInfo(dialog.FileName); opts.LastDirectory = fInfo.DirectoryName; opts.LastOpenedFile = fInfo.Name; // Parse the AFP file if (afpFile.LoadData(dialog.FileName, true)) { // Data bind the list box afpFileBindingSource.DataSource = null; afpFileBindingSource.DataSource = afpFile.Fields; dgvFields.Focus(); // Enable/disable the preview button if there are pages, or the first field is a page segment (resource) DocType = GetFileType(); btnPreview.Enabled = DocType == eFileType.Document || DocType == eFileType.IOCAImage || DocType == eFileType.IMImage; btnManageResources.Enabled = true; // Change form title Text = $"AFP Parser - {fInfo.Name}"; // Create new print parser object for this file printParser = new PrintParser(afpFile); } else if (afpFile.Messages.Any()) { // Something may have went wrong - display any messages string concattedMessages = string.Join($"{Environment.NewLine}* ", afpFile.Messages); MessageBox.Show($"* {concattedMessages}", "Parser Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } finally { Cursor = Cursors.Default; } } }
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { setStacks(); eFileType fileType = FileManagerUtils.GetCurrentPathType(m_currentPath); if (fileType == eFileType.Folder || fileType == eFileType.LogicalDrive) { fillDataGridView(Directory.GetFileSystemEntries(m_currentPath, "*", SearchOption.TopDirectoryOnly)); } else if (fileType == eFileType.File) { System.Diagnostics.Process.Start(m_currentPath); } }
private static void PrefetchNext(string mlvFileName, string content, int count) { MLVCachedReader cache = GetReader(mlvFileName); string nextContent = ""; int currentFrame = 0; eFileType type = eFileType.Unknown; if (count <= 0) { return; } lock (cache.cachedFiles) { if (!cache.cachedFiles.ContainsKey(content)) { return; } type = cache.cachedFiles[content].type; currentFrame = cache.cachedFiles[content].frameNum; } Thread fetchThread = new Thread(() => { foreach (uint frame in GetFrameNumbers(mlvFileName)) { if (frame > currentFrame && count > 0) { nextContent = (currentFrame + 1).ToString("000000") + GetExtension(type); try { GetDataStream(mlvFileName, nextContent, 0); count--; } catch (FileNotFoundException e) { } catch (Exception e) { } currentFrame++; } } }); fetchThread.Name = "Prefetch: " + mlvFileName + " " + content; fetchThread.Start(); }
private static bool checkIfFileTypeIsLogicalDrive(string i_CurrentPath, ref eFileType i_FileType) { string[] logicalDrives = Environment.GetLogicalDrives(); bool state = false; foreach (var drive in logicalDrives) { if (drive.Equals(i_CurrentPath)) { i_FileType = eFileType.LogicalDrive; state = true; } } return(state); }
public IRead Get(eFileType type) { IRead read = null; switch (type) { case eFileType.RichTextDocument: read = new RichTextDocument(); break; case eFileType.WordDocument: read = new WordDocument(); break; case eFileType.TextDocument: read = new TextDocument(); break; } return(read); }
public static eFileType GetCurrentPathType(string i_CurrentPath) { eFileType fileType = eFileType.Invalid; if (checkIfFileTypeIsLogicalDrive(i_CurrentPath, ref fileType)) { return(fileType); } try { FileAttributes attributes = File.GetAttributes(i_CurrentPath); fileType = attributes.HasFlag(FileAttributes.Directory) ? eFileType.Folder : eFileType.File; } catch (Exception e) { fileType = eFileType.Invalid; } return(fileType); }
private static void PrefetchSave(string mlvFileName, string content, eFileType type, int frame, byte[] stream) { MLVCachedReader cache = GetReader(mlvFileName); CleanCache(); lock (cache.cachedFiles) { if (!cache.cachedFiles.ContainsKey(content)) { CachedFile cachedFile = new CachedFile(); cachedFile.lastUseTime = DateTime.Now; cachedFile.name = content; cachedFile.bufferedData = stream; cachedFile.type = type; cachedFile.frameNum = frame; cache.cachedFiles.Add(content, cachedFile); } } }
//------------------------------------------------ private IEnumerator loadResource(string name, string path, eFileType type) { WWW www = new WWW(path); yield return(www); switch (type) { case eFileType.eFile_Mark: { _tempMark = www.texture; break; } case eFileType.eFile_Wally: { _tempWally = www.texture; break; } default: { break; } } www.Dispose(); www = null; _loadCount--; //load if (_loadCount == 0) { _isProcessing = false; _wallyMgr.newWally(ref _tempMark, ref _tempWally); } }
/// <summary> /// Initialize dictionary object, then depending on efile type, initialize delegate and to load data in dictionary and return dictionary /// </summary> /// <param name="Filename"></param> /// <param name="extension"></param> /// <returns>Dictonary<int, CityInfo></int></returns> public Dictionary <int, CityInfo> ParseFile(string Filename, eFileType extension) { // clean FileData dictionary FileData = new Dictionary <int, CityInfo>(); // create the delegate SetupDataFile setupData = null; // switch on extension type to assign the correct method to the delegate switch (extension) { case eFileType.CSV: { setupData = ParseCSV; break; } case eFileType.JSON: { setupData = ParseJSON; break; } case eFileType.XML: { setupData = ParseXML; break; } } // call delegate and return the parsed data setupData(Filename); SortDictionary(); return(FileData); }
private static string GetExtension(eFileType type) { switch (type) { case eFileType.Dng: return(".DNG"); case eFileType.Fits: return(".FITS"); case eFileType.Wav: return(".WAV"); case eFileType.MJpeg: return(".MJPEG"); case eFileType.Jpg: return(".JPG"); case eFileType.Txt: return(".TXT"); } return(""); }
public WaveFileReader(FileStream stream, eFileType type) { InputStream = stream; Type = type; switch (Type) { case eFileType.WAV: // Open the destination .wav file Reader = new BinaryReader(InputStream); WavHeader = new WaveHeader(); WavHeader.Read(Reader); DataStartPos = InputStream.Seek(0, SeekOrigin.Current); SamplingRate = WavHeader.fmt.sampleRate; break; case eFileType.RawIQ: case eFileType.CFile: Reader = new BinaryReader(InputStream); break; } }
public RtsaFileReader(string fileName, eFileType type) : this(File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { }
public cFeedBackMessage Run() { if (this.Input == null) { FeedBackMessage.IsSucceed = false; FeedBackMessage.Message = "No input data defined."; return FeedBackMessage; } string PathForImages; if (IsDisplayUIForFilePath) { SaveFileDialog CurrSaveFileDialog = new SaveFileDialog(); CurrSaveFileDialog.Filter = "CSV file (*.csv)|*.csv| XLS file (*.xls)|*.xls| ARFF file (*.arff)|*.arff"; System.Windows.Forms.DialogResult Res = CurrSaveFileDialog.ShowDialog(); if (Res != System.Windows.Forms.DialogResult.OK) { FeedBackMessage.IsSucceed = false; FeedBackMessage.Message = "Incorrect File Name."; return FeedBackMessage; } FilePath = CurrSaveFileDialog.FileName; if (CurrSaveFileDialog.FilterIndex == 1) this.FileType = eFileType.CSV; else if (CurrSaveFileDialog.FilterIndex == 2) this.FileType = eFileType.XLS; else this.FileType = eFileType.ARFF; } else if (IsIncludeImageAsComment) { this.FileType = eFileType.XLS; var dlg1 = new Ionic.Utils.FolderBrowserDialogEx(); dlg1.Description = "Create a folder that will contain your file and the images."; dlg1.ShowNewFolderButton = true; dlg1.ShowEditBox = true; //dlg1.NewStyle = false; // dlg1.SelectedPath = txtExtractDirectory.Text; dlg1.ShowFullPathInEditBox = true; dlg1.RootFolder = System.Environment.SpecialFolder.Desktop; // Show the FolderBrowserDialog. DialogResult result = dlg1.ShowDialog(); if (result != DialogResult.OK) { FeedBackMessage.IsSucceed = false; FeedBackMessage.Message = "Incorrect File Name."; return FeedBackMessage; } PathForImages = dlg1.SelectedPath; if (Directory.Exists(PathForImages) == false) { FeedBackMessage.IsSucceed = false; FeedBackMessage.Message = "Incorrect File Name."; return FeedBackMessage; } } else { if (this.FilePath == "") { FeedBackMessage.IsSucceed = false; FeedBackMessage.Message = "Incorrect File Name."; return FeedBackMessage; } } if (this.FileType == eFileType.CSV) { if (IsTagToBeSaved == false) { using (StreamWriter myFile = new StreamWriter(FilePath, this.IsAppend, Encoding.Default)) { // Export titles: string sHeaders = ""; if (this.Input.ListRowNames != null) sHeaders += this.Separator; for (int j = 0; j < this.Input.Count; j++) { sHeaders = sHeaders.ToString() + this.Input[j].Name + Separator; } sHeaders = sHeaders.Remove(sHeaders.Length - 1); myFile.WriteLine(sHeaders); // Export data. for (int i = 0; i < this.Input[0].Count; i++) { string stLine = ""; if ((this.Input.ListRowNames != null) && (this.Input.ListRowNames.Count > i)) stLine += this.Input.ListRowNames[i] + this.Separator; for (int j = 0; j < this.Input.Count; j++) { stLine = stLine.ToString() + this.Input[j][i] + Separator; } stLine = stLine.Remove(stLine.Length - 1); myFile.WriteLine(stLine); } myFile.Close(); } } } else if (this.FileType == eFileType.XLS) { // ExportToExcel(this.Input, FilePath, PathForImages); //Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); //Microsoft.Office.Interop.Excel.Workbook xlWorkBook; //Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet; //object misValue = System.Reflection.Missing.Value; //// xlApp = new Excel.ApplicationClass(); //xlWorkBook = xlApp.Workbooks.Add(misValue); //xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //// Microsoft.Office.Interop.Excel.Range cell = GetMyPictureCELL(taperSheet); ////xlWorkSheet.Cells[j + 2, 1].AddComment(" "); ////xlWorkSheet.Cells[j + 2, 1].Comment.Shape.Fill.UserPicture(imagenames[j]); //xlWorkBook.SaveAs(FilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, // Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); //xlWorkBook.Close(true, misValue, misValue); //xlApp.Quit(); //releaseObject(xlWorkSheet); //releaseObject(xlWorkBook); //releaseObject(xlApp); } else if (this.FileType == eFileType.ARFF) { Instances insts = this.Input.CreateWekaInstances(); ArffSaver saver = new ArffSaver(); CSVSaver savercsv = new CSVSaver(); saver.setInstances(insts); saver.setFile(new java.io.File(FilePath)); saver.writeBatch(); // System.Diagnostics.Process proc1 = new System.Diagnostics.Process(); // proc1.StartInfo.FileName = "C:\\Program Files\\Weka-3-6\\RunWeka.bat explorer"; // proc1.StartInfo.Arguments = FilePath; // proc1.Start(); } if (this.IsRunEXCEL) { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = "excel"; proc.StartInfo.Arguments = FilePath; proc.Start(); } return FeedBackMessage; }
public cFeedBackMessage Run() { if (this.Input == null) { FeedBackMessage.IsSucceed = false; FeedBackMessage.Message = "No input data defined."; return FeedBackMessage; } if (IsDisplayUIForFilePath) { SaveFileDialog CurrSaveFileDialog = new SaveFileDialog(); CurrSaveFileDialog.Filter = "CSV file (*.csv)|*.csv| XLS file (*.xls)|*.xls"; System.Windows.Forms.DialogResult Res = CurrSaveFileDialog.ShowDialog(); if (Res != System.Windows.Forms.DialogResult.OK) { FeedBackMessage.IsSucceed = false; FeedBackMessage.Message = "Incorrect File Name."; return FeedBackMessage; } FilePath = CurrSaveFileDialog.FileName; if (CurrSaveFileDialog.FilterIndex == 0) this.FileType = eFileType.CSV; else this.FileType = eFileType.XLS; } if (this.FileType == eFileType.CSV) { using (StreamWriter myFile = new StreamWriter(FilePath, false, Encoding.Default)) { // Export titles: string sHeaders = ""; if (this.Input.ListRowNames != null) sHeaders += this.Separator; for (int j = 0; j < this.Input.Count; j++) { sHeaders = sHeaders.ToString() + this.Input[j].Name + Separator; } sHeaders = sHeaders.Remove(sHeaders.Length - 1); myFile.WriteLine(sHeaders); // Export data. for (int i = 0; i < this.Input[0].Count; i++) { string stLine = ""; if (this.Input.ListRowNames != null) stLine += this.Input.ListRowNames[i] + this.Separator; for (int j = 0; j < this.Input.Count; j++) { stLine = stLine.ToString() + this.Input[j][i] + Separator; } stLine = stLine.Remove(stLine.Length - 1); myFile.WriteLine(stLine); } myFile.Close(); } } else if (this.FileType == eFileType.XLS) { ExportToExcel(this.Input, FilePath); //Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); //Microsoft.Office.Interop.Excel.Workbook xlWorkBook; //Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet; //object misValue = System.Reflection.Missing.Value; //// xlApp = new Excel.ApplicationClass(); //xlWorkBook = xlApp.Workbooks.Add(misValue); //xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //// Microsoft.Office.Interop.Excel.Range cell = GetMyPictureCELL(taperSheet); ////xlWorkSheet.Cells[j + 2, 1].AddComment(" "); ////xlWorkSheet.Cells[j + 2, 1].Comment.Shape.Fill.UserPicture(imagenames[j]); //xlWorkBook.SaveAs(FilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, // Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); //xlWorkBook.Close(true, misValue, misValue); //xlApp.Quit(); //releaseObject(xlWorkSheet); //releaseObject(xlWorkBook); //releaseObject(xlApp); } if (this.IsRunEXCEL) { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = "excel"; proc.StartInfo.Arguments = FilePath; proc.Start(); } return FeedBackMessage; }
public void LoadParameters(string[] Params) { string _currentArgName = "", _currentArgValue = ""; foreach (string _param in Params) { // Get the arg name and value _currentArgName = _param.Split('=')[0].ToUpper(); if (_param.Split('=').Length == 2) { _currentArgValue = _param.Split('=')[1]; } else if (_param.Split('=').Length > 2) { throw new Exception($"Wrong argument: {_param}"); } else { _currentArgValue = ""; } // Identify arg name switch (_currentArgName) { case "DB_SERVER": DBServer = _currentArgValue; break; case "DB_USER": DBUser = _currentArgValue; break; case "DB_PASSWORD": DBPassword = _currentArgValue; break; case "DB_DATABASE": DBDataBase = _currentArgValue; break; case "DB_TIMEOUT": DBTimeOut = Int32.Parse(_currentArgValue); break; case "MAIL_SERVER": MailServer = _currentArgValue; break; case "MAIL_USER": MailUser = _currentArgValue; break; case "MAIL_PASSWORD": MailPassword = _currentArgValue; break; case "SUBJECT": MailSubject = _currentArgValue; break; case "TO": MailTo = _currentArgValue; break; case "ERR_TO": MailErrorTo = _currentArgValue; break; case "QUERY": if (!String.IsNullOrEmpty(_currentArgValue)) { ProcessQuery = Convert.ToInt32(_currentArgValue); } break; case "SUBQUERY": if (!String.IsNullOrEmpty(_currentArgValue)) { ProcessSubQuery = Convert.ToInt32(_currentArgValue); } break; case "PARAMS": ProcessParams = _currentArgValue; break; case "FONTSIZE": if (!String.IsNullOrEmpty(_currentArgValue)) { ProcessFontSize = Convert.ToInt32(_currentArgValue); } break; case "NOBAND": ProcessNoBand = true; break; case "NOEMPTY": ProcessNoEmpty = true; break; case "EMPTYMESSAGE": ProcessEmptyMessage = _currentArgValue; break; case "FILENAME": ProcessFileName = _currentArgValue; break; case "FILETYPE": Enum.TryParse(_currentArgValue, out eFileType _fileType); ProcessFileType = _fileType; break; case "ORIENTATION": Enum.TryParse(_currentArgValue, out ePageOrientation _pageOrientation); ProcessPageOrientation = _pageOrientation; break; default: throw new Exception($"Wrong argument: {_currentArgName}"); } } }
private static string GetExtension(eFileType type) { switch (type) { case eFileType.Dng: return ".DNG"; case eFileType.Fits: return ".FITS"; case eFileType.Wav: return ".WAV"; case eFileType.MJpeg: return ".MJPEG"; case eFileType.Jpg: return ".JPG"; case eFileType.Txt: return ".TXT"; } return ""; }
public void SetFilePath(string path) { mpath = string.Copy(path); mft = DetermineFileType(path); }
unsafe protected eFileType DetermineFileType(string source_path_filename) { eFileType result = eFileType.eUnknown; mlogger.TraceEvent(LogLevels.Verbose, 33001, "Determining file type of {0}", source_path_filename); if (!File.Exists(source_path_filename)) // file is not there or no permissions { mlogger.TraceEvent(LogLevels.Warning, 33002, "Cannot access file {0}", source_path_filename); return(result); } FileInfo fi; try { fi = new System.IO.FileInfo(source_path_filename); } catch (Exception e) { mlogger.TraceException(e); return(result); } if (//(fi.Attributes & FileAttributes.Compressed) == FileAttributes.Compressed || fi.Extension.ToLower().Equals(".zip") | fi.Extension.ToLower().Equals(".zipx") | fi.Extension.ToLower().Equals(".7z")) { result = eFileType.eZip; mlogger.TraceEvent(LogLevels.Warning, 33039, "Compressed archive use is unavailable today {0}", source_path_filename); return(result); } FileStream stream; BinaryReader reader; byte[] buff; try { stream = fi.OpenRead(); reader = new BinaryReader(stream); buff = new byte[stream.Length]; } catch (Exception e) { mlogger.TraceException(e); return(result); } int thisread = 0; string str2, str2a, str2b; if (stream.Length < CALIBRATION_SAVE_RESTORE.Length) { mlogger.TraceEvent(LogLevels.Info, 33003, "Skipping this tiny file"); reader.Close(); return(result); } else if (stream.Length >= DETECTOR_SAVE_RESTORE.Length) { thisread = reader.Read(buff, 0, DETECTOR_SAVE_RESTORE.Length); // cannot throw due to length check under normal circumstances, so this is ok str2 = System.Text.ASCIIEncoding.ASCII.GetString(buff, 0, thisread); stream.Seek(0, SeekOrigin.Begin); thisread = reader.Read(buff, 0, INTEGRATED_REVIEW.Length); str2a = System.Text.ASCIIEncoding.ASCII.GetString(buff, 0, thisread); stream.Seek(0, SeekOrigin.Begin); thisread = reader.Read(buff, 0, OLD_REVIEW.Length); str2b = System.Text.ASCIIEncoding.ASCII.GetString(buff, 0, thisread); } else { mlogger.TraceEvent(LogLevels.Info, 33004, "Skipping this small file"); reader.Close(); return(result); } if (str2.Equals(DETECTOR_SAVE_RESTORE)) { result = eFileType.eInitialDataDetector; mlogger.TraceEvent(LogLevels.Info, 33009, "The file {0} is an initial data file with detector parameters", source_path_filename); } else if (str2a.Equals(INTEGRATED_REVIEW)) { result = eFileType.eNCC; mlogger.TraceEvent(LogLevels.Info, 33009, "The file {0} is a Radiation Review data file", source_path_filename); } else if (str2b.Equals(OLD_REVIEW)) { result = eFileType.eOldNCC; mlogger.TraceEvent(LogLevels.Info, 33009, "The file is an olde-style Radiation Review data file"); } else { mlogger.TraceEvent(LogLevels.Verbose, 33010, "The file is not an initial data file with detector parameters, or an NCC file"); stream.Seek(0, SeekOrigin.Begin); bool found = false; foreach (INCCFileExt fe in System.Enum.GetValues(typeof(INCCFileExt))) { if (fe < INCCFileExt.CALIB_PARAMETER_EXT && Extensions[(int)fe] == (fi.Extension.ToUpper())) { found = true; } } if (!found) { mlogger.TraceEvent(LogLevels.Verbose, 33011, "The file is not an initial data calibration or transfer file, suffix mismatch"); } else { bool calSuffix = false; calSuffix = Extensions[(int)INCCFileExt.CALIBRATION_EXT].Equals(fi.Extension.ToUpper()); if (calSuffix) { mlogger.TraceEvent(LogLevels.Verbose, 33012, "The file may be an initial data calibration or transfer file"); thisread = reader.Read(buff, 0, CALIBRATION_SAVE_RESTORE.Length); if (thisread > 0) { str2 = System.Text.ASCIIEncoding.ASCII.GetString(buff, 0, thisread); // emtpy string result should be ok here if (str2.Equals(CALIBRATION_SAVE_RESTORE)) { result = eFileType.eInitialDataCalibration; mlogger.TraceEvent(LogLevels.Info, 33013, "The file {0} is an initial data calibration file", source_path_filename); } } } else { mlogger.TraceEvent(LogLevels.Verbose, 33014, "The file may be a transfer file"); } if (result == eFileType.eUnknown) // check for transfer file now { stream.Seek(0, SeekOrigin.Begin); results_rec results = new results_rec(); double db_version = 5.0; int sz = Marshal.SizeOf(results); byte[] los_bytos = TransferUtils.TryReadBytes(reader, sz); if (los_bytos != null) fixed(byte *pData = los_bytos) { results = *(results_rec *)pData; } else { mlogger.TraceEvent(LogLevels.Warning, 33096, "Results not read", source_path_filename); reader.Close(); return(result); } if (results.db_version != db_version) { old_results_rec old_results = new old_results_rec(); sz = Marshal.SizeOf(old_results); stream.Seek(0, SeekOrigin.Begin); los_bytos = TransferUtils.TryReadBytes(reader, sz); if (los_bytos != null) { mlogger.TraceEvent(LogLevels.Verbose, 33015, "The file may be an older transfer file, from an earlier INCC version"); mlogger.TraceEvent(LogLevels.Warning, 33016, "Cannot use file {0}, not a version 5 result", source_path_filename); } else { mlogger.TraceEvent(LogLevels.Info, 33017, ("The file is not an older transfer file")); } reader.Close(); return(result); } else { mlogger.TraceEvent(LogLevels.Verbose, 33018, "The file may be a current INCC transfer file"); } string[] nums; stream.Seek(0, SeekOrigin.Begin); thisread = reader.Read(buff, 0, 9); // gotta be 9 here, I think the previous results read guarantees that str2 = System.Text.ASCIIEncoding.ASCII.GetString(buff, 0, thisread); nums = str2.Split(new char[] { '.' }, 3); // if the first 9 bytes are a date "11.08.05\0" followed by a null, then we likely have one // todo: make a better test, use the DateTimeFrom, it checks more bytes, and do a file suffix check for the meas type too if ((buff[8] == 0x0) && (nums.Length == 3)) { result = eFileType.eTransfer; mlogger.TraceEvent(LogLevels.Verbose, 33019, "The file is a likely a transfer file"); } else { mlogger.TraceEvent(LogLevels.Verbose, 33020, "The file is not a transfer file"); } } // transfer file content check } // transfer file or ini data cal content check } // transfer file or ini data cal suffix check try { reader.Close(); } catch (Exception e) { if (mlogger != null) { mlogger.TraceException(e); } } return(result); }
public CLIDynamicFile(eFileType fileType) { FileType = fileType; }
public WaveFileWriter(string fileName, eFileType type) : this(File.Open(fileName, FileMode.Create, FileAccess.Write), type) { }
public static byte[] GetDataStream(string mlvFileName, string content, int prefetchCount) { MLVCachedReader cache = GetReader(mlvFileName); eFileType type = GetFileType(content); lock (cache.cachedFiles) { if (cache.cachedFiles.ContainsKey(content)) { PrefetchNext(mlvFileName, content, prefetchCount - 1); cache.cachedFiles[content].lastUseTime = DateTime.Now; return(cache.cachedFiles[content].bufferedData); } } switch (type) { case eFileType.Txt: string info = GetInfoFields(mlvFileName).Aggregate <string>(addString); return(ASCIIEncoding.ASCII.GetBytes(info)); case eFileType.Wav: return(GetWaveDataStream(mlvFileName)); case eFileType.MJpeg: return(GetMJpegDataStream(mlvFileName)); } int frame = GetFrameNumber(mlvFileName, content); /* read video frame with/out debayering dependig on filetype */ switch (type) { case eFileType.Dng: case eFileType.Fits: cache.handler.DebayeringEnabled = false; break; case eFileType.Jpg: cache.handler.DebayeringEnabled = true; break; } byte[] data = null; Bitmap currentFrame = null; MLVTypes.mlv_vidf_hdr_t vidfHeader = new MLVTypes.mlv_vidf_hdr_t(); /* seek to the correct block */ int block = cache.reader.GetVideoFrameBlockNumber((uint)frame); if (block < 0) { throw new FileNotFoundException("Requested video frame " + frame + " but thats not in the file index"); } /* ensure that multiple threads dont conflict */ lock (cache) { /* read it */ cache.reader.CurrentBlockNumber = block; cache.handler.VidfHeader.blockSize = 0; cache.reader.ReadBlock(); /* now the VIDF should be read correctly */ if (cache.handler.VidfHeader.blockSize == 0) { throw new InvalidDataException("Requested video frame " + frame + " but the index points us wrong"); } /* get all data we need */ switch (type) { case eFileType.Dng: case eFileType.Fits: data = cache.handler.RawPixelData; vidfHeader = cache.handler.VidfHeader; break; case eFileType.Jpg: if (cache.handler.CurrentFrame != null) { currentFrame = new Bitmap(cache.handler.CurrentFrame); } break; } } /* process it */ switch (type) { case eFileType.Fits: { object[] metadata = cache.reader.GetVideoFrameMetadata((uint)frame); byte[] stream = FITSCreator.Create(mlvFileName, vidfHeader, data, metadata); PrefetchSave(mlvFileName, content, eFileType.Dng, frame, stream); PrefetchNext(mlvFileName, content, prefetchCount); return(stream); } case eFileType.Dng: { object[] metadata = cache.reader.GetVideoFrameMetadata((uint)frame); byte[] stream = DNGCreator.Create(mlvFileName, vidfHeader, data, metadata); PrefetchSave(mlvFileName, content, eFileType.Dng, frame, stream); PrefetchNext(mlvFileName, content, prefetchCount); return(stream); } case eFileType.Jpg: { JpegBitmapEncoder encoder = new JpegBitmapEncoder(); Stream stream = new MemoryStream(); encoder.QualityLevel = 90; if (currentFrame != null) { encoder.Frames.Add(BitmapFrame.Create(BitmapSourceFromBitmap(currentFrame))); encoder.Save(stream); stream.Seek(0, SeekOrigin.Begin); } stream.Seek(0, SeekOrigin.Begin); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream.Close(); PrefetchSave(mlvFileName, content, eFileType.Jpg, frame, buffer); PrefetchNext(mlvFileName, content, prefetchCount); return(buffer); } } throw new FileNotFoundException("Requested frame " + frame + " of type " + type + " but we dont support that"); }
public SoundFileSink(eFileType type, Control displayControl) { FileType = type; switch (FileType) { case eFileType.MP3: FileName = "audio.mp3"; break; case eFileType.WAV: FileName = "audio.wav"; break; } StatusLabel = new Label(); StatusLabel.Text = FileName + ": Writer idle"; //StatusLabel.Dock = DockStyle.Fill; SaveAsButton = new Button(); SaveAsButton.Text = "Save As..."; SaveAsButton.Click += (object sender, EventArgs e) => { SaveFileDialog dlg = new SaveFileDialog(); switch (FileType) { case eFileType.MP3: dlg.Filter = "MP3 File (*.mp3)|*.mp3|All files (*.*)|*.*"; break; case eFileType.WAV: dlg.Filter = "WAV File (*.wav)|*.wav|All files (*.*)|*.*"; break; } if (dlg.ShowDialog() == DialogResult.OK) { try { try { File.Delete(dlg.FileName); } catch (Exception ex) { } FileName = dlg.FileName; if (Started) { Stop(); Start(); } } catch (Exception ex) { MessageBox.Show("Could not create file: " + ex.GetType().ToString()); } } }; Status = ""; SplitContainer split = new SplitContainer(); split.Orientation = System.Windows.Forms.Orientation.Horizontal; split.SplitterDistance = 60; split.Panel1.Controls.Add(StatusLabel); split.Panel2.Controls.Add(SaveAsButton); displayControl.Controls.Add(split); }