private IEnumerable <FileInfo> GetSortedFilesByType(TypeOfFile typeOfFile) { var dirPath = String.Empty; if (typeOfFile == TypeOfFile.User) { dirPath = Path.Combine(UserEFToolsDir.FullName, _subdirectoryName); } else if (typeOfFile == TypeOfFile.VS) { dirPath = Path.Combine(VSEFToolsDir.FullName, _subdirectoryName); } Debug.Assert(!String.IsNullOrEmpty(dirPath), "We should have determined the dirPath for extensible files"); if (!String.IsNullOrEmpty(dirPath)) { var dirInfo = new DirectoryInfo(dirPath); if (dirInfo.Exists) { foreach (var fileInfo in GetSortedFilesByExtension(dirInfo.GetFiles(), _extension)) { yield return(fileInfo); } } } }
public UpdateInfo(string pName, string pFolderPath, string pUpdatePath, string pTagName, TypeOfFile pTypeOfFile) { Name = pName; FolderPath = pFolderPath; UpdatePath = pUpdatePath; TagName = pTagName; TypeOfFile = pTypeOfFile; }
/// <summary> /// Used to create input text file by taking type of file, templateName and fileextension as input. /// </summary> /// <param name="typeOfFile","templateName","fileextension">type of file</param> /// <returns>success or error message</returns> public static string GenerateInputDataTextfile(TypeOfFile typeOfFile, string templateName, string fileextension) { string projectPath = string.Empty; string path = Directory.GetCurrentDirectory(); var patharray = path.Split('\\'); int length = patharray.Length; for (int i = 0; i <= length - 4; i++) { projectPath = projectPath + patharray[i] + "\\"; } projectPath = projectPath + @"BnPBaseFramework.IO"; string schemaText = string.Empty; string result = "Error"; StringBuilder jsonSchemaPath = new StringBuilder(); string inputDataPath = string.Empty; try { if (ConfigurationManager.AppSettings["JsonSchema"] != null) { jsonSchemaPath.Append(ConfigurationManager.AppSettings["JsonSchema"]); jsonSchemaPath.Append(@"\"); jsonSchemaPath.Append(typeOfFile.ToString() + @"\"); jsonSchemaPath.Append(typeOfFile.ToString() + @"_InputTextFiles"); jsonSchemaPath.Append(@"\"); jsonSchemaPath.Append(templateName); if (File.Exists(jsonSchemaPath.ToString())) { string[] Input = File.ReadAllLines(jsonSchemaPath.ToString()); OutputFilePath = projectPath + @"\DapStuff\" + typeOfFile + ".txt"; if (File.Exists(OutputFilePath)) { File.WriteAllLines(OutputFilePath, Input); result = "Data Inserted into the file Successfully"; } else { File.AppendAllLines(OutputFilePath, Input); result = "Data Inserted into the file Successfully"; } } } } catch (FileNotFoundException ex) { result = ex.Message; } return(result); }
/// <summary> /// Used to create batch file by taking type of file as input. /// </summary> /// <param name="typeOfFile">type of file</param> /// <returns>success or error message</returns> public static string CreateBatchFile(TypeOfFile typeOfFile) { string projectPath = string.Empty; Process process = null; try { string path = Directory.GetCurrentDirectory(); var patharray = path.Split('\\'); int length = patharray.Length; for (int i = 0; i <= length - 4; i++) { projectPath = projectPath + patharray[i] + "\\"; } projectPath = projectPath + @"BnPBaseFramework.IO"; StringBuilder pushD, config, fileName, script; pushD = new StringBuilder(); pushD.Append(projectPath); pushD.Append(ConfigurationManager.AppSettings[typeOfFile.ToString() + "PushD"]); pushD.Append("\n"); config = new StringBuilder(); config.Append(projectPath); config.Append(ConfigurationManager.AppSettings[typeOfFile.ToString() + "Config"]); fileName = new StringBuilder(); fileName.Append(projectPath); fileName.Append(ConfigurationManager.AppSettings[typeOfFile.ToString() + "FileName"]); fileName.Append("\n"); script = new StringBuilder(); script.Append("pushd "); script.Append(pushD); script.Append("DAPConsoleProcessor.exe /K -config "); script.Append(config); script.Append(" -filename "); script.Append(fileName); // script.Append("pause"); File.WriteAllText(projectPath + @"\DapStuff\Brierley.DataAcquisition" + "\\" + typeOfFile.ToString() + "File.bat", script.ToString()); result = "Success"; } catch (Exception ex) { Console.WriteLine(ex.Message); if (process != null) { process.Close(); } result = ex.Message; } return(result); }
public void DownloadFile(TypeOfFile typeOfFile) { switch (typeOfFile) { case TypeOfFile.Image: TempImageClass tempImageClass = new TempImageClass(); tempImageClass.url = url; tempImageClass.preview = image; tempImageClass.OnDownloadCompleted = () => { LoadingManager.HideLoadingScreen(); }; TexturesSaver.QueueForDownload(tempImageClass); break; } }
private void openRuleFile(object sender, EventArgs e) { Stream myStream; OpenFileDialog openFile = new OpenFileDialog(); standartSettingsForFile(openFile, "dat files (*.dat)|*.dat", 2, true); if (openFile.ShowDialog() != DialogResult.OK) { return; } if ((myStream = openFile.OpenFile()) == null) { showError("Не удалось открыть файл!", "Ошибка открытия файла"); return; } //Проверка на наличие количества информации в начале файла, //чтобы в идентифицировать файл: файл признаков или файл правил. if (myStream.Length < 4) { showError("Файл меньше 4 байт!", "Ошибка размера файла"); return; } using (BinaryReader binaryStream = new BinaryReader(myStream)) { TypeOfFile typeReadFile = (TypeOfFile)binaryStream.ReadInt32(); if (typeReadFile != TypeOfFile.rules) { showError("Данный файл не является файлом с правилами!", "Ошибка типа файла"); return; } rulesDB.Items.Clear(); while (binaryStream.BaseStream.Position < binaryStream.BaseStream.Length || binaryStream.PeekChar() > -1) { ListViewItem item = new ListViewItem(); item.Text = binaryStream.ReadString(); item.SubItems.Add(binaryStream.ReadString()); rulesDB.Items.Add(item); } } }
public void UpdateScreenData(ILootLockerStageData stageData) { asset = stageData as InventoryAssetResponse.DemoAppAsset; if (asset != null) { if (asset.files != null && asset.files.Length > 0) { url = asset.files.Last().url; TypeOfFile filetype = GetFileType(url); downloadFileBtn.onClick.AddListener(() => { LoadingManager.ShowLoadingScreen(); DownloadFile(filetype); }); } } }
public TypeOfFile GetFileType(string fileLink) { string[] filesArray = fileLink.Split('.'); string ext = filesArray.Last(); TypeOfFile fileType = TypeOfFile.Image; if (imageExtenstions.Contains(ext)) { typeOfFile.text = "Avatar Image"; fileType = TypeOfFile.Image; } else if (assetBundle.Contains(ext)) { typeOfFile.text = "Asset Bundle"; fileType = TypeOfFile.AssetBundle; } else if (scene.Contains(ext)) { typeOfFile.text = "Scene File"; fileType = TypeOfFile.AssetBundle; } return(fileType); }
private ObservableCollection <ITSVGenericModel> LoadListFromFile(string pPath, TypeOfFile pTypeOfFile) { ObservableCollection <ITSVGenericModel> list = new ObservableCollection <ITSVGenericModel>(); try { string str3 = File.OpenText(pPath).ReadToEnd(); char[] separator = new char[] { Convert.ToChar(13) }; string[] strArray2 = str3.Split(separator, StringSplitOptions.RemoveEmptyEntries); //this.SetLog(string.Format("Loading {0} from File {1}......", strArray2.Length, str2)); for (int i = 0; i < strArray2.Length; i++) { try { if (!string.IsNullOrWhiteSpace(strArray2[i].Trim())) { switch (pTypeOfFile) { case TypeOfFile.DSSTE: list.Add(new DSSTableExplorerChannelInformation(strArray2[i])); break; case TypeOfFile.STB: list.Add(new STBScannerChannelInformation(strArray2[i])); break; case TypeOfFile.GCT: list.Add(new GCTChannelInformation(strArray2[i])); break; default: break; } } } catch (Exception exception) { //this.SetLog(string.Format("Error loading File {0} at Line {1}. Error Message: {2}", str2, i + 1, exception.Message)); } } return(new ObservableCollection <ITSVGenericModel>(list.Distinct <ITSVGenericModel>(new FullComparisson()).OrderBy(p => p.MinorNumber).OrderBy(p => p.MajorNumber))); } catch (Exception exception2) { //this.SetLog(string.Format("Error cargando el archivo {1}: {0}", exception2.Message, pPath)); return(list); } }
private ObservableCollection <ITSVGenericModel> LoadListFromDirectory(string pPath, TypeOfFile pTypeOfFile) { ObservableCollection <ITSVGenericModel> list = new ObservableCollection <ITSVGenericModel>(); List <string> list2 = new List <string>(); list2.AddRange(Directory.GetDirectories(pPath)); foreach (var item in list2) { list = new ObservableCollection <ITSVGenericModel>(list.Union(LoadListFromDirectory(item, pTypeOfFile))); } list2.Clear(); string[] strArray = new string[] { "*.tsv", "*.txt" }; foreach (string str in strArray) { list2.AddRange(Directory.GetFiles(pPath, str)); } foreach (var item in list2) { list = new ObservableCollection <ITSVGenericModel>(list.Union(LoadListFromFile(item, pTypeOfFile))); } return(new ObservableCollection <ITSVGenericModel>(list.Distinct <ITSVGenericModel>(new FullComparisson()).OrderBy(p => p.MinorNumber).OrderBy(p => p.MajorNumber))); }
public FileInformation(string FullPath, string FileName, TypeOfFile typeOfFile) { this.FullPath = FullPath; this.FileName = FileName; this.TypeOfFile = typeOfFile; }
/// <summary> /// method to generate random input data based on json template /// </summary> /// <param name="typeOfFile"></param> /// <param name="templateName"></param> /// <returns></returns> public static string GenerateInputData(TypeOfFile typeOfFile, string templateName) { string schemaText = string.Empty; string result = "Error"; StringBuilder jsonSchemaPath = new StringBuilder(); string inputDataPath = string.Empty; try { if (ConfigurationManager.AppSettings["JsonSchema"] != null) { jsonSchemaPath.Append(ConfigurationManager.AppSettings["JsonSchema"]); jsonSchemaPath.Append(@"\"); jsonSchemaPath.Append(typeOfFile.ToString() + @"\"); jsonSchemaPath.Append(typeOfFile.ToString() + @"_JSONTemplates"); if (jsonSchemaPath != null) { inputDataPath = jsonSchemaPath.ToString().Replace("JSONTemplates", "InputTextFiles"); jsonSchemaPath.Append(@"\"); jsonSchemaPath.Append(templateName); jsonSchemaPath.Append(".JSON"); string outPutFilePath = inputDataPath + "\\" + templateName + ".txt"; try { if (File.Exists(outPutFilePath)) { File.Delete(outPutFilePath); } } catch (FileNotFoundException ex) { result = ex.Message; } using (var r = new StreamReader(jsonSchemaPath.ToString())) { schemaText = r.ReadToEnd(); } dynamic dynObj = JsonConvert.DeserializeObject(schemaText); foreach (var data in dynObj.Files) { foreach (var data1 in data.TypeOfFiles) { JObject dObject = data1; var delimiter = Convert.ToString(dObject["Delimiter"]); var noOfRows = Convert.ToInt32(dObject["No_Of_Rows"]); StringBuilder inputDataStore = null; DataTable dataTable = null; int loyalCount = 0; while (noOfRows > 0) { int propertiesCount = 2; inputDataStore = new StringBuilder(); foreach (var item in dObject.Properties()) { var attributeName = item.Name; string[] chkList = { "Delimiter", "No_Of_Rows", "Directive" }; if (attributeName == "Directive") { var directiveItem = item.Value.Last; var directive = Convert.ToString(((Newtonsoft.Json.Linq.JValue)directiveItem.First).Value); inputDataStore.Append(directive); inputDataStore.Append(delimiter); } else if (Array.IndexOf(chkList, attributeName) < 0) { var first = item.Value.First; var last = item.Value.Last; var firstValue = Convert.ToString(((Newtonsoft.Json.Linq.JValue)first.First).Value); var lastValue = Convert.ToString(((Newtonsoft.Json.Linq.JValue)last.First).Value); int startIndex = firstValue.IndexOf('['); int endIndex = firstValue.IndexOf(']'); var attributeType = firstValue.Substring(0, startIndex).ToUpper(); var attributeRange = firstValue.Substring(startIndex + 1, endIndex - startIndex - 1); var attributeRequired = lastValue.Replace("{", "").Replace("}", "").ToUpper(); int length = 0; uint minLength = 0, maxLength = 0; string regexExp = string.Empty; if (attributeType == "STRING" && attributeRange.Contains("-")) { minLength = Convert.ToUInt16(attributeRange.Split('-')[0]); maxLength = Convert.ToUInt16(attributeRange.Split('-')[1]); } else if (attributeType == "INT") { length = Convert.ToInt32(attributeRange); } else if (attributeType == "DATABASEVALUE") { //if (loyalCount == 0) //{ dataTable = GetDBValue(attributeRange.Split('-')[0], attributeName, attributeRange.Split('-')[1], null); //} } else if (attributeType == "REGULAREXP") { string parse = @firstValue.Replace("RegularExp[", ""); regexExp = parse.Substring(0, parse.Length - 1).Replace("\"", @"\"); } else if (attributeType == "STRING" && !attributeRange.Contains('-')) { minLength = Convert.ToUInt32(attributeRange); } switch (attributeType) { #region Integer case "INT": if (attributeRequired == "TRUE") { switch (attributeName) { case "Status": { inputDataStore.Append((int)Eric.Morrison.RandomValue.GetRandomEnumValue <Status>()); } break; case "StoreType": { inputDataStore.Append((int)Eric.Morrison.RandomValue.GetRandomEnumValue <StoreType>()); } break; default: { inputDataStore.Append(RandomNumber(length)); } break; } } break; #endregion #region RegularExpressionValidator case "REGULAREXP": { if (attributeRequired == "TRUE") { if (Regex.IsMatch(CreateEmail(), regexExp, RegexOptions.IgnoreCase)) { inputDataStore.Append(CreateEmail()); } } break; } #endregion #region string case "STRING": if (attributeRequired == "TRUE") { if (maxLength == 0) { switch (attributeName) { case "Password": { inputDataStore.Append(CreatePassword(minLength)); break; } default: { inputDataStore.Append(Eric.Morrison.RandomString.Get(minLength, true)); break; } } } else { inputDataStore.Append(Eric.Morrison.RandomString.Get(minLength, maxLength, true)); } } break; #endregion #region Date case "DATE": if (attributeRequired == "TRUE") { DateTime dateTime = System.DateTime.Now.AddDays(-1); inputDataStore.Append(dateTime.ToString("dd-MMM-yy HH.mm.ss tt")); } break; #endregion #region Double case "DOUBLE": { if (attributeRequired == "TRUE") { System.Random random = new System.Random(); inputDataStore.Append(Math.Round(random.NextDouble(), 2).ToString("0.00")); } } break; #endregion #region DbValue case "DATABASEVALUE": { if (attributeRequired == "TRUE") { if ((attributeRange.Split('-')[1]) == "ALL") { string number = (RandomNumber(10)); DataTable dtTxnHeaderId = GetDBValue(attributeRange.Split('-')[0], attributeName, attributeRange.Split('-')[1], number); while (Convert.ToInt32(dtTxnHeaderId.Rows[0][0]) == 0) { inputDataStore.Append(number); break; } } else { inputDataStore.Append(dataTable.Rows[loyalCount][0]); } } } break; #endregion } if (propertiesCount - 1 < dObject.Properties().Count()) { inputDataStore.Append(delimiter); } } propertiesCount++; } System.IO.File.AppendAllText(outPutFilePath, inputDataStore.ToString() + Environment.NewLine); result = "Success"; noOfRows--; loyalCount++; } } } } } } catch (Exception ex) { result = ex.Message; } return(result); }
/// <summary> /// Saves to file. /// </summary> /// <param name="content">The content.</param> /// <param name="fileName">Name of the file.</param> /// <param name="separteFolder">if set to <c>true</c> [separte folder].</param> /// <param name="typeOfFile">The type of file.</param> public static void SaveToFile(string content, string fileName = "file", bool separteFolder = false, TypeOfFile typeOfFile = TypeOfFile.Text) { var currentDirectory = Directory.GetCurrentDirectory(); string fileExtentsion; switch (typeOfFile) { case TypeOfFile.Text: fileExtentsion = ".txt"; break; case TypeOfFile.Csv: fileExtentsion = ".csv"; break; default: fileExtentsion = ".txt"; break; } if (separteFolder) { var folderPath = Path.Combine(currentDirectory, fileName); Directory.CreateDirectory(folderPath); var pathWithFileName = Path.Combine(folderPath, AppendTimeStamp(fileName + fileExtentsion)); File.WriteAllText(pathWithFileName, content); } else { var pathWithFileName = Path.Combine(currentDirectory, AppendTimeStamp(fileName + fileExtentsion)); File.WriteAllText(pathWithFileName, content); } }
public Element(string FullPath, string FileName, TypeOfFile typeOfFile) { this.FullPath = FullPath; this.FileName = FileName; this.TypeOfFile = typeOfFile; }
public void Process() { _inputFileName = Path.GetFileName(_inputFilePath); if (!File.Exists(_inputFilePath)) { Console.WriteLine($"ERROR : File Does not exists : {_inputFilePath}"); return; } //Setting Default Directory if (string.IsNullOrEmpty(_outputFilePath) || string.IsNullOrWhiteSpace(_outputFilePath)) { //_outputFilePath = _def } if (string.IsNullOrEmpty(_outputFileName) || string.IsNullOrWhiteSpace(_outputFileName)) { //_outputFileName = $"{}"; } //Setting Default FileName //Getting Directory name of input file and creating directory for processed files //_inputFileDirectoryPath = new DirectoryInfo(InputFilePath).Parent.FullName; //_processedDirectoryPath = Path.Combine(_inputFileDirectoryPath, processedDirectoryName); if (!Directory.Exists(_outputFilePath)) { //Directory.CreateDirectory(_outputFilePath); } _processFileType = TypeOfFile.TransactionLogFile; switch (_processFileType) { case TypeOfFile.TransactionLogFile: Console.WriteLine($"Transaction log File process starting : {_inputFileName} "); // debug the error SPACE IN THE FOLDER NAME WILL GIVE ERROR, WIILE WRITING CONTENTS TO THE FILE //TextFileProcessor textProcessor = new TextFileProcessor(_inputFilePath, @"C: \Users\Ambati\OneDrive\Learning.Net and projects\Projects\Files and Streams\Folder Test\output\myoutputfile.txt"); TextFileProcessor textProcessor = new TextFileProcessor(_inputFilePath, @"C:\Users\Ambati\Desktop\outputfile\myoutputfile.txt"); textProcessor.process(); break; case TypeOfFile.BatchLogFile: Console.WriteLine($"Batch log File process starting DOES NOT EXITS: {_inputFileName} "); break; case TypeOfFile.CsvFile: //Console.WriteLine($" CSV File process starting DOES NOT EXITS: {_inputFileName} "); //CsvFileProcessor csvProcessor = new CsvFileProcessor(_inputFilePath, @"C:\Users\Ambati\Desktop\outputfile\myoutputfile.txt"); //csvProcessor.Process(); break; default: Console.WriteLine($"ERROR : There is no CODE to process this \"{_inputFileName}\" type"); break; } }
private IEnumerable<FileInfo> GetSortedFilesByType(TypeOfFile typeOfFile) { var dirPath = String.Empty; if (typeOfFile == TypeOfFile.User) { dirPath = Path.Combine(UserEFToolsDir.FullName, _subdirectoryName); } else if (typeOfFile == TypeOfFile.VS) { dirPath = Path.Combine(VSEFToolsDir.FullName, _subdirectoryName); } Debug.Assert(!String.IsNullOrEmpty(dirPath), "We should have determined the dirPath for extensible files"); if (!String.IsNullOrEmpty(dirPath)) { var dirInfo = new DirectoryInfo(dirPath); if (dirInfo.Exists) { foreach (var fileInfo in GetSortedFilesByExtension(dirInfo.GetFiles(), _extension)) { yield return fileInfo; } } } }