public static void Decompress(FileInfo archFile, out String szOutFile) { Logger.Enter(); using (FileStream archFileStream = archFile.OpenRead()) { String currentFileName = archFile.FullName; String newFileName = currentFileName.Remove( currentFileName.Length - archFile.Extension.Length); using (FileStream normalFileStream = File.Create(newFileName)) { using (GZipStream decompressionStream = new GZipStream(archFileStream, CompressionMode.Decompress)) { byte[] buffer = new byte[1024]; int nRead; while ((nRead = decompressionStream.Read(buffer, 0, buffer.Length)) > 0) { normalFileStream.Write(buffer, 0, nRead); } szOutFile = newFileName; Console.WriteLine("Decompressed: {0}", archFile.Name); } } } Logger.Leave(); }
public void SettingUpdatesProperties() { FileInfo testFile = new FileInfo(GetTestFilePath()); testFile.Create().Dispose(); Assert.All(TimeFunctions(requiresRoundtripping: true), (tuple) => { DateTime dt = new DateTime(2014, 12, 1, 12, 0, 0, tuple.Item3); tuple.Item1(testFile.FullName, dt); var result = tuple.Item2(testFile.FullName); Assert.Equal(dt, result); Assert.Equal(dt.ToLocalTime(), result.ToLocalTime()); // File and Directory UTC APIs treat a DateTimeKind.Unspecified as UTC whereas // ToUniversalTime treats it as local. if (tuple.Item3 == DateTimeKind.Unspecified) { Assert.Equal(dt, result.ToUniversalTime()); } else { Assert.Equal(dt.ToUniversalTime(), result.ToUniversalTime()); } }); }
public static string GetFileName(string filePath) { if(string.IsNullOrEmpty(filePath)) return ""; FileInfo fileInfo = new FileInfo(filePath); return (fileInfo != null) ? fileInfo.Name : ""; }
public static Excel LoadExcel(string path) { FileInfo file = new FileInfo(path); ExcelPackage ep = new ExcelPackage(file); Excel xls = new Excel(ep.Workbook); return xls; }
public void FalseForDirectory() { string fileName = GetTestFilePath(); Directory.CreateDirectory(fileName); FileInfo di = new FileInfo(fileName); Assert.False(di.Exists); }
public void Length_Of_Directory_Throws_FileNotFoundException() { string path = GetTestFilePath(); Directory.CreateDirectory(path); FileInfo info = new FileInfo(path); Assert.Throws<FileNotFoundException>(() => info.Length); }
// Ex: C:\Users\Public\Test\blah.txt would return C:\Users\Public\Test\ public static string GetDirectoryPath(string filePath) { if(string.IsNullOrEmpty(filePath)) return ""; FileInfo fileInfo = new FileInfo(filePath); return (fileInfo != null) ? fileInfo.Directory.FullName : ""; }
void LoadMapping() { FileInfo theSourceFile = new FileInfo (path); StreamReader reader = theSourceFile.OpenText(); string text = reader.ReadToEnd(); reader.Close(); string[] lines = text.Split('\r'); Client_lowerLeft_x = float.Parse(lines[1]); Client_lowerLeft_y = float.Parse(lines[2]); Client_lowerRight_x = float.Parse(lines[3]); Client_lowerRight_y = float.Parse(lines[4]); Client_upperRight_x = float.Parse(lines[5]); Client_upperRight_y = float.Parse(lines[6]); Client_upperLeft_x = float.Parse(lines[7]); Client_upperLeft_y = float.Parse(lines[8]); Server_lowerLeft_x = float.Parse(lines[10]); Server_lowerLeft_y = float.Parse(lines[11]); Server_lowerRight_x = float.Parse(lines[12]); Server_lowerRight_y = float.Parse(lines[13]); Server_upperRight_x = float.Parse(lines[14]); Server_upperRight_y = float.Parse(lines[15]); Server_upperLeft_x = float.Parse(lines[16]); Server_upperLeft_y = float.Parse(lines[17]); }
public static Package Parse(FileInfo assemblyInfoFile) { try { var lines = Storage.ReadAllLines(assemblyInfoFile.FullName); var title = AssemblyInfo.GetData(lines, AssemblyInfoData.AssemblyTitle); var projectFile = assemblyInfoFile.Directory.Parent.GetFiles(title + "*.csproj").SingleOrDefault(); if (projectFile == null) { return null; } var targetFramework = ExtractTargetFramework(projectFile); var version = AssemblyInfo.GetData(lines, AssemblyInfoData.AssemblyVersion); var nuspec = projectFile.Directory.GetFiles("Package.nuspec").SingleOrDefault(); if (nuspec == null) { return new Package(projectFile, assemblyInfoFile, lines, title, version, targetFramework); } return new Package(projectFile, assemblyInfoFile, lines, title, version, targetFramework, nuspec); } catch (Exception exception) { throw new IOException($"Cannot parse the file {assemblyInfoFile.FullName}.", exception); } }
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(onError); // Loading all configs files ConfigMgr.LoadConfigs(); Config = ConfigMgr.GetConfig<LauncherConfig>(); // Loading log level from file if (!Log.InitLog(Config.LogLevel, "LauncherServer")) ConsoleMgr.WaitAndExit(2000); Client = new RpcClient("LauncherServer", Config.RpcInfo.RpcLocalIp, 1); if (!Client.Start(Config.RpcInfo.RpcServerIp, Config.RpcInfo.RpcServerPort)) ConsoleMgr.WaitAndExit(2000); Info = new FileInfo("Configs/mythloginserviceconfig.xml"); if (!Info.Exists) { Log.Error("Configs/mythloginserviceconfig.xml", "Config file missing !"); ConsoleMgr.WaitAndExit(5000); } StrInfo = Info.OpenText().ReadToEnd(); if (!TCPManager.Listen<TCPServer>(Config.LauncherServerPort, "LauncherServer")) ConsoleMgr.WaitAndExit(2000); Server = TCPManager.GetTcp<TCPServer>("LauncherServer"); ConsoleMgr.Start(); }
static void CopyFile(string filename, string outputfilename, string pathToBuiltProject) { string strCWD = Directory.GetCurrentDirectory(); string strSource = Path.Combine(Path.Combine(strCWD, SteamAPIRelativeLoc), filename); string strFileDest = Path.Combine(Path.GetDirectoryName(pathToBuiltProject), outputfilename); if (!File.Exists(strSource)) { Debug.LogWarning(string.Format("[Steamworks.NET] Could not copy {0} into the project root. {0} could not be found in '{1}'. Place {0} from the redist into the project root manually.", filename, SteamAPIRelativeLoc)); return; } if (File.Exists(strFileDest)) { if (File.GetLastWriteTime(strSource) == File.GetLastWriteTime(strFileDest)) { FileInfo fInfo = new FileInfo(strSource); FileInfo fInfo2 = new FileInfo(strFileDest); if (fInfo.Length == fInfo2.Length) { return; } } } File.Copy(strSource, strFileDest, true); if (!File.Exists(strFileDest)) { Debug.LogWarning(string.Format("[Steamworks.NET] Could not copy {0} into the built project. File.Copy() Failed. Place {0} from the redist folder into the output dir manually.", filename)); } }
public static void renameFile(DirectoryInfo directory, FileInfo[] files, int i, string nameNumber) { Console.WriteLine(directory.Name); string newName = directory.FullName+@"\"+directory.Name + "-" + nameNumber+((FileInfo)files[i]).Extension; Console.WriteLine(newName); File.Move(((FileInfo)files[i]).FullName, newName); }
void Start() { triviaFile = new FileInfo(Application.dataPath + "/trivia.txt"); if (triviaFile != null && triviaFile.Exists) { reader = triviaFile.OpenText(); } else { embedded = (TextAsset) Resources.Load("trivia_embedded", typeof (TextAsset)); reader = new StringReader(embedded.text); } string lineOfText = ""; int lineNumber = 0; while ( ( lineOfText = reader.ReadLine() ) != null ) { string question = lineOfText; int answerCount = Convert.ToInt32(reader.ReadLine()); List<string> answers = new List<string>(); for (int i = 0; i < answerCount; i++) { answers.Add(reader.ReadLine()); } Trivia temp = new Trivia(question, answerCount, answers); triviaQuestions.Add(temp); lineNumber++; } SendMessage( "BeginGame" ); }
/// <summary> /// A string extension method that save the string into a file. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="file">The FileInfo.</param> /// <param name="append">(Optional) if the text should be appended to file file if it's exists.</param> public static void SaveAs(this string @this, FileInfo file, bool append = false) { using (TextWriter tw = new StreamWriter(file.FullName, append)) { tw.Write(@this); } }
// ------------------------------------------------------------------ // Desc: // ------------------------------------------------------------------ public static exTimebasedCurveInfo Create( string _path, string _name ) { // if ( new DirectoryInfo(_path).Exists == false ) { Debug.LogError ( "can't create asset, path not found" ); return null; } if ( string.IsNullOrEmpty(_name) ) { Debug.LogError ( "can't create asset, the name is empty" ); return null; } string assetPath = Path.Combine( _path, _name + ".asset" ); // check if create the asset FileInfo fileInfo = new FileInfo(assetPath); if ( fileInfo.Exists ) { if ( EditorUtility.DisplayDialog( _name + " already exists.", "Do you want to overwrite the old one?", "Yes", "No" ) == false ) { return null; } } // exTimebasedCurveInfo newCurve = ScriptableObject.CreateInstance<exTimebasedCurveInfo>(); AssetDatabase.CreateAsset(newCurve, assetPath); Selection.activeObject = newCurve; return newCurve; }
public void SymLinkLength() { string path = GetTestFilePath(); string linkPath = GetTestFilePath(); const int FileSize = 2000; using (var tempFile = new TempFile(path, FileSize)) { Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: false)); var info = new FileInfo(path); Assert.Equal(FileSize, info.Length); var linkInfo = new FileInfo(linkPath); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // On Windows, symlinks have length 0. Assert.Equal(0, linkInfo.Length); } else { // On Unix, a symlink contains the path to the target, and thus has that length. // But the length could actually be longer if it's not just ASCII characters. // We just verify it's at least that big, but also verify that we're not accidentally // getting the target file size. Assert.InRange(linkInfo.Length, path.Length, FileSize - 1); } // On both, FileStream should however open the target such that its length is the target length using (FileStream linkFs = File.OpenRead(linkPath)) { Assert.Equal(FileSize, linkFs.Length); } } }
public object Start(string level) { LocalNode node = new LocalNode(Assembly.GetExecutingAssembly()); node.Join(); try { FileInfo levelInfo = new FileInfo(level); if (levelInfo.Directory.Name != "Resources") return "Level is not in a resources directory."; DirectoryInfo directoryInfo = levelInfo.Directory.Parent; World.BaseDirectory = directoryInfo.FullName; World.RuntimeDirectory = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName; using (RuntimeGame game = new RuntimeGame(levelInfo.Name.Substring(0, levelInfo.Name.Length - levelInfo.Extension.Length))) { game.Run(); } } finally { node.Leave(); } return null; }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string sUser = UsuarioWeb.GetNomeUsuarioConectado(Session); if (sUser == "") { Response.Redirect("~/Home.aspx"); } string sPathAnexo = ""; if (Request.QueryString["ANEXO"].ToString() != String.Empty) { sPathAnexo = Request.QueryString["ANEXO"].ToString(); FileInfo finfo = new FileInfo(Server.MapPath("Pedidos//" + sPathAnexo) + ".pdf"); if (finfo.Exists) { sPathAnexo = finfo.FullName; } ShowFile2(sPathAnexo); } } }
/// <summary> /// Initializes a new instance of the <see cref="LogControllerSingletone"/> class. /// </summary> public LogController(string logFilePath) { if((Application.platform == RuntimePlatform.WindowsPlayer)|| (Application.platform == RuntimePlatform.WindowsEditor)) { FileInfo logFileInfo = new FileInfo(logFilePath); FileStream logFile; ///logfile is exist - create FileStream try { logFile = new FileStream(logFilePath,FileMode.Create); _fileNameFull = logFileInfo.FullName; } catch { Debug.LogError("Can not create or open log file"); logFile = null; } ///if error with log File if(logFile == null) _logFileWriter = null; else { ///make buffered stream with 100KB buffer memory _logFileWriter = new StreamWriter(new BufferedStream(logFile,100000)); } WriteLine("log created"); } else { _logFileWriter = null; } }
/// <summary> /// Returns 304 (use cached version) code to the client if /// file was not changed since last request. /// </summary> /// <param name="fileInfo">File location information</param> /// <returns>True if 304 was returned.</returns> public static bool Returned304(FileInfo fileInfo) { if (!fileInfo.Exists) return false; return Returned304(fileInfo.LastWriteTime); }
private void testFile(FileInfo fi) { string fileKey = fi.FullName.Substring(root.Length).Replace('\\','/'); detailData dData = detailMap.ContainsKey(fileKey) ? detailMap[fileKey] : null; string detail = dData != null ? dData.detail : string.Format("<span class=\"infoError\">{0} detail info not found</span>",fileKey); string wUrl = dData != null ? string.Format("check.aspx?w={0}", dData.name) : string.Empty; try { packageLib.BondiWidgetClass widget = new BondiWidgetClass(); //Response.Write(fi.FullName); widget.Load(fi.FullName,"en",false); if (dData.expectPass) Response.Write(string.Format("<tr><td class=\"passed\">PASSED</td><td>{0}</td><td> </td><td><a href=\"{1}\">{2}</a></td></tr>", detail, wUrl,fileKey)); else Response.Write(string.Format("<tr><td class=\"failed\">FAILED</td><td>{0}</td><td>{1}</td><td><a href=\"{2}\">{3}</a></td></tr>", detail, "Widget loaded but test expected FAIL", wUrl, fileKey)); } catch (Exception ex) { if (dData == null || dData.expectPass) { if (dData == null) Response.Write(string.Format("<tr><td class=\"failed\">FAILED</td><td>{0}</td><td>{1}</td><td>{2}</td></tr>", detail, ex.Message, fileKey)); else Response.Write(string.Format("<tr><td class=\"failed\">FAILED</td><td>{0}</td><td>{1}</td><td><a href=\"{2}\">{3}</a></td></tr>", detail, ex.Message, wUrl, fileKey)); } else Response.Write(string.Format("<tr><td class=\"passed\">PASSED</td><td>{0}</td><td>{1}</td><td><a href=\"{2}\">{3}</a></td></tr>", detail, ex.Message, wUrl, fileKey)); } }
public void SelectTextFile(string file) { if (file == "FirstScene") { fileName = file; theSourceFile = new FileInfo ("Assets/Scripts/Dialogue/FirstScene.txt"); reader = theSourceFile.OpenText (); startText = true; } else if (file == "Level1End") { fileName = file; theSourceFile = new FileInfo ("Assets/Scripts/Dialogue/Level1End.txt"); reader = theSourceFile.OpenText (); startText = true; } else if (file == "GoodEnding") { fileName = file; theSourceFile = new FileInfo ("Assets/Scripts/Dialogue/FinalDialogues/GoodEnding.txt"); reader = theSourceFile.OpenText (); startText = true; } else if (file == "BadEnding") { fileName = file; theSourceFile = new FileInfo ("Assets/Scripts/Dialogue/FinalDialogues/BadEnding.txt"); reader = theSourceFile.OpenText (); startText = true; } else { theSourceFile = null; } }
protected static bool IsFileLocked(string fullPath) { FileInfo file = new FileInfo(fullPath); FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { //the file is unavailable because it is: //still being written to //or being processed by another thread //or does not exist (has already been processed) return true; } finally { if (stream != null) stream.Close(); } //file is not locked return false; }
/// <summary> /// プロセスを実行 /// </summary> public void StartProcess(ProcessData procData) { if(procData.use && !procData.IsRunning) { FileInfo fileInfo = new FileInfo(procData.exePath); if(fileInfo.Exists) { Process proc = new Process(); proc.StartInfo.FileName = Path.GetFullPath(procData.exePath); //引数設定 if(procData.argument != "") proc.StartInfo.Arguments = procData.argument; //ウィンドウスタイル設定 if(!ApplicationSetting.Instance.GetBool("IsDebug")) proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; try { proc.Start(); processList.Add(proc); procData.IsRunning = true; } catch(Exception e) { UnityEngine.Debug.Log("ExternalProcess :: process start error - " + e.Message); } } } }
public void WithNoWeaving() { var sourceProjectFile = new FileInfo(@"TestProjects\ProjectWithNoWeaving.csproj"); var targetFileInfo = sourceProjectFile.CopyTo(sourceProjectFile.FullName + "ProjectReaderTest", true); try { var reader = new ProjectReader(targetFileInfo.FullName); Assert.IsNull(reader.DependenciesDirectory); Assert.IsNull(reader.ToolsDirectory); Assert.IsNull(reader.CheckForEquality); Assert.IsNull(reader.CheckForIsChanged); Assert.IsNull(reader.ProcessFields); Assert.IsNull(reader.MessageImportance); Assert.IsNull(reader.TryToWeaveAllTypes); Assert.IsNull(reader.EventInvokerName); Assert.IsNull(reader.EventInvokerName); Assert.IsNull(reader.TargetPath); Assert.IsNull(reader.TargetNode); Assert.IsNull(reader.DependenciesDirectory); } finally { targetFileInfo.Delete(); } }
/// <summary> /// Evaluates and provides the relative path. /// </summary> /// <param name="mainDirPath">The source, or starting location.</param> /// <param name="absoluteFilePath">The location to find.</param> /// <returns></returns> public static string EvaluateRelativePath(this FileInfo mainDirPath, FileInfo absoluteFilePath) { string[] firstPathParts = mainDirPath.FullName.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar); string[] secondPathParts = absoluteFilePath.FullName.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar); int sameCounter = 0; for (int i = 0; i < Math.Min(firstPathParts.Length, secondPathParts.Length); i++) { if (!firstPathParts[i].ToLower().Equals(secondPathParts[i].ToLower())) break; sameCounter++; } if (sameCounter == 0) return absoluteFilePath.FullName; string newPath = String.Empty; for (int i = sameCounter; i < firstPathParts.Length; i++) { if (i > sameCounter) newPath += Path.DirectorySeparatorChar; newPath += ".."; } for (int i = sameCounter; i < secondPathParts.Length; i++) { newPath = String.Format("{0}{1}{2}", newPath, Path.DirectorySeparatorChar, secondPathParts[i]); } return newPath; }
// Use this for initialization void Start() { FileStream file = null; FileInfo fileInfo = null; try { fileInfo = new FileInfo("file.txt"); file = fileInfo.OpenWrite(); for(int i = 0; i < 255; i++) { file.WriteByte((byte)i); } throw new ArgumentNullException("Something bad happened."); } catch(UnauthorizedAccessException e) { Debug.LogWarning(e.Message); } catch (ArgumentNullException e) { //Debug.LogWarning(e.Message); Debug.LogWarning("BAD!!!"); } finally { if (file != null) file.Close(); } }
static void Slice(string sourceFile, string destinationDirectory, int parts) { string extension = new FileInfo(sourceFile).Extension; ext = extension; using (var source = new FileStream(destinationDirectory + sourceFile, FileMode.Open)) { int pieceSize = (int)Math.Ceiling((decimal)source.Length / parts); byte[] buffer = new byte[4096]; for (int i = 1; i <= parts; i++) { string currentFilePath = string.Format(destinationDirectory + "part" + i + extension); using (var destination = new FileStream(currentFilePath, FileMode.Create)) { long partBytes = 0; while (partBytes < pieceSize) { int readBytes = source.Read(buffer, 0, buffer.Length); if (readBytes == 0) { break;; } destination.Write(buffer, 0, readBytes); partBytes += readBytes; } } slicedFiles.Add(currentFilePath); } } }
public void FindLargeFiles(List<string> AllowedExtensions, long MinSize) { foreach (string Filename in Manifest) { FileInfo FI = new FileInfo(Filename); long Size = FI.Length; if (Size > MinSize) { bool bAllowed = false; foreach (string Extension in AllowedExtensions) { if (Filename.EndsWith(Extension, StringComparison.InvariantCultureIgnoreCase)) { bAllowed = true; break; } } if (!bAllowed) { CommandUtils.LogWarning("{0} is {1} with an unexpected extension", Filename, AnalyzeThirdPartyLibs.ToMegabytes(Size)); } } } }
protected void btn_download_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.TableName = "All_Contacts"; using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dlgf"].ConnectionString)) { SqlCommand cmd = new SqlCommand("[CTX].[sp_Select_All_List]", conn); conn.Open(); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(dt); conn.Close(); } string dir = Server.MapPath("All_List_output"); string milli = DateTime.Now.Millisecond.ToString(); FileInfo newFile = new FileInfo(dir + @"\CTX_"+ milli + ".xlsx"); if (newFile.Exists) { newFile.Delete(); // ensures we create a new workbook newFile = new FileInfo(dir + @"\CTX_" + milli + ".xlsx"); } using (ExcelPackage pack = new ExcelPackage(newFile)) { ExcelWorksheet ws = pack.Workbook.Worksheets.Add(dt.TableName.ToString()); ws.Cells["A1"].LoadFromDataTable(dt, true); pack.Save(); } string path = dir + @"\" + newFile.Name; Response.ContentType = "application/excel"; Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + newFile.Name + "\""); //file name must be in double quotes to allow spaces in the filename Response.TransmitFile(path); Response.End(); }
public Animation[] animations; //num_animation个 /////////////////////////////////////////////////////////////////////////////////////////////////////////// public ABI(string filename) { this.filename = filename; FileInfo fi = new FileInfo(filename); this.filename = fi.Name; using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { using (BinaryReader br = new BinaryReader(fs)) { int sign = br.ReadInt32();; Debug.Assert(sign == 0x424d444c); version = int.Parse(ConvertBytesToString(br.ReadBytes(4))); Debug.Assert(version == 1060 || version == 1050, "此ABI文件的版本不是1050或1060!"); num_timeaxis = br.ReadInt32(); num_animation = br.ReadInt32(); num_texture = br.ReadInt32(); /////////////////////////////////////////////////////////////////////////////////////////////////////////// //所有贴图 textureinfos = new TextureInfo[num_texture]; for (int i = 0; i < num_texture; i++) { textureinfos[i] = new TextureInfo(); textureinfos[i].UNKNOWN = br.ReadInt32(); textureinfos[i].width = br.ReadInt32(); textureinfos[i].height = br.ReadInt32(); textureinfos[i].name = ConvertBytesToString(br.ReadBytes(32)); textureinfos[i].palette = new uint[256]; for (int j = 0; j < 256; j++) { uint r = br.ReadByte(); uint g = br.ReadByte(); uint b = br.ReadByte(); textureinfos[i].palette[j] = 0xff000000 | (r << 16) | (g << 8) | b; } textureinfos[i].data = br.ReadBytes(textureinfos[i].width * textureinfos[i].height); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// //模型数据 if (version != 1050) { br.ReadByte(); //未知标志,并不恒为1,奇怪的是,1050格式里面没有这个自己,而1060却有 } //Debug.Assert(br.ReadByte() == 1); num_model = br.ReadInt32(); num_bone = br.ReadInt32(); models = new Model[num_model]; for (int i = 0; i < num_model; i++) { Model d = models[i] = new Model(); d.num_vertice = br.ReadInt32(); d.num_polygon = br.ReadInt32(); d.name = ConvertBytesToString(br.ReadBytes(32)); d.vertex = new Vertex[d.num_vertice]; for (int j = 0; j < d.num_vertice; j++) { Vertex v = d.vertex[j] = new Vertex(); v.X = br.ReadSingle(); v.Y = br.ReadSingle(); v.Z = br.ReadSingle(); } d.polygon = new Polygon[d.num_polygon]; for (int j = 0; j < d.num_polygon; j++) { Polygon poly = d.polygon[j] = new Polygon(); poly.num_lines = br.ReadByte(); if (poly.num_lines != 3 && poly.num_lines != 4) { //的确存在num_lines超过3/4的情况,比方说tiger.abi,num_lines就有为6的情况 //throw new Exception(); } poly.texture_id = br.ReadByte(); poly.map_points = new Point[poly.num_lines]; for (int k = 0; k < poly.num_lines; k++) { Point p = poly.map_points[k] = new Point(); p.vertex_id = br.ReadInt16(); p.U = br.ReadInt16() / 4096f; p.V = br.ReadInt16() / 4096f; } } d.vbt = new VidToBoneTable(); d.vbt.entry = new VidToBoneTableEntry[num_bone]; for (int j = 0; j < num_bone; j++) { d.vbt.entry[j] = new VidToBoneTableEntry(); d.vbt.entry[j].StartVidx = br.ReadInt32(); d.vbt.entry[j].EndVidx = br.ReadInt32(); //要不要-1? } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// //骨骼继承结构 hierarchy = new BoneHierarchy[num_bone]; for (int i = 0; i < num_bone; i++) { hierarchy[i] = new BoneHierarchy(); hierarchy[i].ParentIdx = br.ReadInt32(); hierarchy[i].GlobalOffset = new Vector3( br.ReadSingle(), br.ReadSingle(), br.ReadSingle()); hierarchy[i].NodeName = ConvertBytesToString(br.ReadBytes(32)); hierarchy[i].UNKNOWN = br.ReadInt32(); Debug.WriteLine(String.Format("{0} - [{1}]:{2}", i, hierarchy[i].ParentIdx, hierarchy[i].NodeName)); Debug.Assert(hierarchy[i].UNKNOWN == 0); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// //关键帧、时间轴相关结构 timeaxises = new TransformTimeAxis[num_timeaxis]; for (int i = 0; i < num_timeaxis; i++) { TransformTimeAxis ta = timeaxises[i] = new TransformTimeAxis(); ta.trta = new TranslateTimeAxis(); ta.rta = new RotateTimeAxis(); TranslateTimeAxis tta = ta.trta; tta.num_keyframe = br.ReadInt32(); tta.tkf = new TranslateKeyFrame[tta.num_keyframe]; for (int j = 0; j < tta.num_keyframe; j++) { tta.tkf[j] = new TranslateKeyFrame(); tta.tkf[j].timestamp = br.ReadByte(); tta.tkf[j].translate = new Vector3(br.ReadInt16() / 256f, br.ReadInt16() / 256f, br.ReadInt16() / 256f); } RotateTimeAxis rta = ta.rta; rta.num_keyframe = br.ReadInt32(); rta.rkf = new RotateKeyFrame[rta.num_keyframe]; for (int j = 0; j < rta.num_keyframe; j++) { rta.rkf[j] = new RotateKeyFrame(); rta.rkf[j].timestamp = br.ReadByte(); rta.rkf[j].rotate = new Quaternion(br.ReadInt16() / 32768f, br.ReadInt16() / 32768f, br.ReadInt16() / 32768f, br.ReadInt16() / 32768f); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// //动画行为定义结构 animations = new Animation[num_animation]; for (int i = 0; i < num_animation; i++) { Animation ani = animations[i] = new Animation(); ani.name = ConvertBytesToString(br.ReadBytes(0x3c)); ani.num_related_bone = br.ReadInt32(); ani.bae = new BoneAnimationEntry[ani.num_related_bone]; for (int j = 0; j < ani.num_related_bone; j++) { BoneAnimationEntry bae = ani.bae[j] = new BoneAnimationEntry(); bae.bone_id = br.ReadInt32(); bae.transform_time_axis_idx = br.ReadInt32(); bae.tta = timeaxises[bae.transform_time_axis_idx]; } } Debug.WriteLine("已读长度: " + fs.Position.ToString()); Debug.WriteLine("文件长度: " + fs.Length.ToString()); } //GenerateAllBitmaps(); //创建所有位图 } }
/// <summary> /// Inserts a set of keywords got from a FileInfo object into the 'keywords' collection /// </summary> /// <param name="keywords">The keyword collection</param> /// <param name="fileInfo">The FileInfo object</param> public static void GetKeywords(Dictionary <string, string> keywords, FileInfo fileInfo) { GetKeywords(keywords, "", fileInfo); }
/// <summary> /// Method Scans the curr dir. /// </summary> static void ScanCurrDir() { int total = 0; WriteLine("-- Directory Scanner --"); WriteLine(); ForegroundColor = Blue; WriteLine($"[*] Scan Started At {Globals.CurrentDateTime}"); ResetColor(); // getting filenames var files = Directory.GetFiles(CurrentDirectory, "*", SearchOption.AllDirectories); // instacing misc to store misc files var misc = new System.Collections.Generic.List <string>(); var isMisc = false; // flag to check if any misc file foreach (var file in files) { if (++total > 5000) // safeguard api calls { ForegroundColor = Red; WriteLine("You reached 5000/per day scan limit"); WriteLine("If you try to scan again then your API may be blocked"); ResetColor(); Exit(1); } var fileInfo = new FileInfo(file); if (fileInfo.Length < 1.28e+8) // safeguard file size { ForegroundColor = Yellow; WriteLine($"[~] Scanning {fileInfo.FullName}"); ResetColor(); var report = Report(Globals.GetSHA256(fileInfo.FullName)); if (report.ResponseCode == FileReportResponseCode.Present) { // execute detection and format detection if file is present on server int detected = 0; foreach (var av in report.Scans.Keys) { if (report.Scans[av].Detected) { detected++; } } FormatDetection(detected); } // otherwise misc file is not there or is being scanned else if (report.ResponseCode == FileReportResponseCode.Queued) { // file is queued ForegroundColor = Magenta; WriteLine("[!] Not found - Misc File"); ResetColor(); } else { ForegroundColor = Magenta; WriteLine("[!] Not found - Misc File"); ResetColor(); var scan = SendScan(fileInfo); misc.Add($"{scan.SHA256}|{fileInfo.FullName}"); // adding to misc file isMisc = true; //break; } WriteLine($"[#] Next Scan At {Now.AddSeconds(30):dd/MM/yyyy hh:mm:ss tt}"); Sleep(30000); // sleep to prevent spamming } else { ForegroundColor = Yellow; WriteLine($"[!] Skipping {fileInfo.FullName} - Beyond 128mB"); ResetColor(); } } ForegroundColor = Blue; WriteLine($"[*] Scan Completed At {Globals.CurrentDateTime}"); ResetColor(); if (isMisc) { // writing misc files File.WriteAllLines(Globals.MiscFile, misc.ToArray()); WriteLine(); WriteLine("We found some miscellaneous files"); WriteLine($"Try scaning misc file after {Now.AddHours(5):dd/MM/yyyy hh:mm:ss tt}"); } }
private void DoSearch() { UpdateStatueBarTextSafe("开始搜索"); Invalidate(); richTextBoxEx1.Clear(); if (string.IsNullOrEmpty(excelPath)) { richTextBoxEx1.SelectedText = "请先点击'绑定目录'选择绑定table文件夹"; return; } int itemCount = 0; foreach (var file in Directory.GetFiles("./cache/")) { var fileInfo = new FileInfo(file); if (file.EndsWith(".txt")) { using (StreamReader sr = new StreamReader(file, Encoding.UTF8)) { string line; int lineIndx = 0; while ((line = sr.ReadLine()) != null) { var targetPos = line.IndexOf(textBox1.Text); var sizeStr = textBox1.Text.Length; bool isTarget = false; int tabIndex = 0; while (targetPos >= 0) { if (!isTarget) { // 第一次进入先拼一个表头 richTextBoxEx1.SelectionColor = Color.Red; var fileNames = fileInfo.Name.Replace(".txt", "").Split('-'); if (fileNames[0].Length > 8) { fileNames[0] = fileNames[0].Substring(0, 8); } if (fileNames[1].Length > 8) { fileNames[1] = fileNames[1].Substring(0, 8); } richTextBoxEx1.SelectedText = string.Format("{0,-8}\t{1,-8}\t#{2:####}\t", fileNames[0], fileNames[1], lineIndx + 14); richTextBoxEx1.SelectionColor = Color.Black; } if (targetPos > 0) { var pickText = line.Substring(0, targetPos); richTextBoxEx1.SelectedText = pickText; tabIndex += GetAppearTimes(pickText, "\t"); } richTextBoxEx1.InsertLink(line.Substring(targetPos, sizeStr), string.Format("{0}#{1}#{2}", fileInfo.Name, lineIndx + 14, tabIndex)); line = line.Substring(targetPos + sizeStr); targetPos = line.IndexOf(textBox1.Text); isTarget = true; } if (isTarget) { richTextBoxEx1.SelectedText = line + "\n"; itemCount++; if (itemCount >= 1000) { UpdateStatueBarTextSafe(string.Format("搜索结束:记录数达到上限,共找到记录{0}条", itemCount)); //最多出1000条,抱歉 return; } } lineIndx++; } } } } UpdateStatueBarTextSafe(string.Format("搜索结束:共找到记录{0}条", itemCount)); //防止link点击后乱跳转的bug this.richTextBoxEx1.Select(0, 0); }
public void FailConfigurationSet(FileInfo config) { Trace.Write("Tests failed\n\n"); //Trace.WriteLine(""); }
public void PassConfigurationSet(FileInfo config) { Trace.Write("All passed\n\n"); }
public void RunningConfigurationSet(FileInfo config) { Trace.Write("{config}\n".Replace(new { config })); }
static void Main(string[] args) { string file = @"d:\IT\testfile.txt"; Console.WriteLine("Path osztály:"); Console.WriteLine("Path.GetFileName(path): " + Path.GetFileName(file)); Console.WriteLine("Path.GetExtension(path): " + Path.GetExtension(file)); Console.WriteLine("Path.GetDirectoryName(path): " + Path.GetDirectoryName(file)); Console.WriteLine("\nDirectory osztály:"); Console.WriteLine(@"Directory.CreateDirectory(@'C:\FolderName1\FolderName2\...')"); //Directory.CreateDirectory(@"C:\"); var folderPath = @"C:\"; var filePath = @"C:\Windows"; Console.WriteLine($"\nAdd vissza az összes mappát-t innen: {folderPath}"); foreach (var item in Directory.GetDirectories(folderPath)) { Console.WriteLine(item); } Console.WriteLine($"\nAdd vissza az összes file-t innen: {filePath}"); foreach (var item in Directory.GetFiles(filePath)) { Console.WriteLine(Path.GetFileName(item)); } var comb1 = @"d:\IT\Proba\Eleres"; var comb2 = @"files\test.txt"; Console.WriteLine($"\nÖsszefűzése 2 elérési útnak: {comb1} és {comb2}"); Console.WriteLine(Path.Combine(comb1, comb2)); var fldr1 = @"d:\IT\test\üres mappa\"; var fldr2 = @"d:\IT\test\nem üres mappa\"; var dex = Directory.Exists(comb1); Console.WriteLine($"\nDirectory.Exists('{comb1}') >>>>> {dex} "); //Directory.CreateDirectory(fldr1); //Directory.CreateDirectory(fldr2); Console.WriteLine($"Directory.Create('{fldr1}') >> Mappaszerkezet létrehozása"); Console.WriteLine($"Directory.Delete('{fldr1}') >> Csak akkor töröl, ha üres a mappa!"); Console.WriteLine($"Directory.Delete('{fldr2}', true) >> Minden esetben törli a mappát, a tartalmával együtt!"); //Directory.Delete(fldr1, true); //Directory.Delete(fldr2, true); string sourceDirectory = @"d:\IT\test\mappa1\testfile.txt"; string destinationDirectory = @"d:\\IT\\mappa20\testfile.txt"; Console.WriteLine("Filok, mappák másolása:"); /* * try * { * Directory.Move(sourceDirectory, destinationDirectory); * } * catch (Exception e) * { * Console.WriteLine(e.Message); * } */ var myPath = @"d:\ELADÓ CUCCOK\"; // listSubfolderFiles(myPath); //Console.WriteLine($"Directory.Move('{copyFrom}', '{pasteTo}'"); var myFile = @"D:\IT\test\BH4K8270.jpg"; var myFile2 = @"D:\IT\test\H.jpg"; FileInfo info = new FileInfo(myFile); long length = info.Length; var fileSize = Convert.ToString(length); float asd = (length / 1024 / 1024); var fileSize2 = Math.Round(asd, 2); Console.WriteLine($"File neve: {Path.GetFileName(myFile)}"); Console.WriteLine($"File kiterjesztése: {Path.GetExtension(myFile)}"); Console.WriteLine($"File mérete: {fileSize} byte"); Console.WriteLine($"File mérete: {fileSize2} MB"); Console.WriteLine($"File GetCreationTime: {File.GetCreationTime(myFile)}"); Console.WriteLine($"File GetCreationTimeUtc: {File.GetCreationTimeUtc(myFile)}"); Console.WriteLine($"File GetLastAccessTime: {File.GetLastAccessTime(myFile)}"); Console.WriteLine($"File GetLastAccessTimeUtc: {File.GetLastAccessTimeUtc(myFile)}"); Console.WriteLine($"File GetLastWriteTime: {File.GetLastWriteTime(myFile)}"); Console.WriteLine($"File GetLastWriteTimeUtc: {File.GetLastWriteTimeUtc(myFile)}"); var oldDate = File.GetLastWriteTimeUtc(myFile); var newDate = oldDate; Console.WriteLine($"Old Date: {oldDate}"); Console.WriteLine($"New Date {newDate}"); /* * newDate = newDate.AddYears(1); * newDate = newDate.AddMonths(1); * newDate = newDate.AddDays(1); * newDate = newDate.AddHours(1); * newDate = newDate.AddMinutes(1); * newDate = newDate.AddSeconds(1); */ Console.WriteLine($"New Date {newDate}"); var str = File.ReadAllLines(myFile); Console.WriteLine(str); File.SetLastWriteTimeUtc(myFile, newDate); Console.WriteLine($"File GetLastWriteTimeUtc: {File.GetLastWriteTimeUtc(myFile)}"); Console.ReadLine(); }
/// <summary> /// Initializes a new instance of the <see cref="XmlObject"/> class /// for reading and/or writing. /// /// If the file does not exists it will be created. /// </summary> /// <exception cref="ArgumentNullException"> /// When <paramref name="fallbackxmlcontent"/> or <paramref name="xmlfilename"/> is <see langword="null"/> or <see cref="string.Empty"/>. /// </exception> /// <param name="xmlfilename"> /// The name of the XML File to load into the <see cref="XmlObject"/>. /// </param> /// <param name="fallbackxmlcontent"> /// The fallback content string to write into the fallback XML File /// if the file does not exist or if the file is empty. /// </param> /// <param name="saveToCurrentDirectory"> /// Controls weather to save the file to the xmlfilename param string if /// it is the full path or to the Current Directory if it supplies file name only. /// This implies that that file is saved to the fully qualified path of the /// current working directory prefixed before the filename. /// </param> public XmlObject(string xmlfilename, string fallbackxmlcontent, bool saveToCurrentDirectory) { if (string.IsNullOrEmpty(xmlfilename)) { throw new ArgumentNullException(nameof(xmlfilename) /*, "'xmlfilename' cannot be null or empty."*/); } if (string.IsNullOrEmpty(fallbackxmlcontent)) { throw new ArgumentNullException(nameof(fallbackxmlcontent) /*, "'fallbackxmlcontent' cannot be null or empty."*/); } this.ObjLock = new object(); this.ElementsAdded = new Dictionary <string, XmlElementData>(); this.ElementsEdits = new Dictionary <string, XmlElementData>(); this.ElementAttributesDeleted = new Dictionary <string, XmlElementData>(); this.ElementsDeleted = new List <string>(); if (saveToCurrentDirectory) { var directory = new DirectoryInfo(xmlfilename); if (!directory.Parent.Exists) { throw new DirectoryNotFoundException(Resources.XmlObject_Directory_Not_Found); } #if NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48 || NETCOREAPP2_0 || NETSTANDARD2_0 if (!xmlfilename.Contains(Directory.GetCurrentDirectory()) && #else if (!xmlfilename.Contains(Directory.GetCurrentDirectory(), StringComparison.Ordinal) && #endif directory.Parent.FullName == Directory.GetCurrentDirectory()) { xmlfilename = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + xmlfilename; } } #if NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48 || NETCOREAPP2_0 || NETSTANDARD2_0 if (!fallbackxmlcontent.Contains("<?xml version=\"1.0\" encoding=\"utf-8\" ?>")) #else if (!fallbackxmlcontent.Contains("<?xml version=\"1.0\" encoding=\"utf-8\" ?>", StringComparison.Ordinal)) #endif { // insert root element at begginning of string data. fallbackxmlcontent = fallbackxmlcontent.Insert(0, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); } long fileSize = 0; this.CachedXmlfilename = xmlfilename; if (!xmlfilename.Equals(":memory", StringComparison.Ordinal)) { this.Exists = File.Exists(xmlfilename); this.HasChanged = !this.Exists; var fileinfo = new FileInfo(xmlfilename); if (!fileinfo.Directory.Exists) { throw new DirectoryNotFoundException(Resources.XmlObject_Directory_Not_Found); } if (this.Exists) { fileSize = fileinfo.Length; } } this.Doc = fileSize > 0 ? XDocument.Load(xmlfilename) : XDocument.Parse(fallbackxmlcontent); }
public CommonFile(FileInfo location) { this.Location = location; }
static void Main() { try { Dialogue.Message("Hello world! I, " + Environment.MachineName + ", will be your narrator for tonight."); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Fileselect()); if (Global.Continue) { Prompt = new Prompt(); var Folder = new FileInfo(Global.Path).Directory; foreach (FileInfo f in Folder.GetFiles()) { if (f.FullName.EndsWith(".lpc")) { Containers.Add(new FileList(f.FullName)); } else if (f.FullName.EndsWith(".lpv")) { Vars.Add(new OptionSet(f.FullName)); } } Interpreter.Sysinit(); foreach (OptionSet S in Vars) { Memory.Init(S); } Application.Run(Prompt); Containers.Clear(); foreach (Container C in Interpreter.Containers) { if (!C.Sys) { File.WriteAllText(Folder.FullName + "\\" + C.Name + ".lpc", null); FileList f = new FileList(Folder.FullName + "\\" + C.Name + ".lpc"); f.newElement("%%" + C.Path); if (C.AttatchedEngine() != null) { f.newElement("##" + C.AttatchedEngine().Name + "," + C.AttatchedEngine().Action); } foreach (Pipe p in C.Attatched) { f.newElement(p.Name); } Containers.Add(f); } } foreach (FileList F in Containers) { F.reload(); } OptionSet s = new OptionSet(Folder.FullName + "\\vars.lpv"); foreach (Memory.Var v in Memory.Vars) { s.NewEntry(v.name, v.value); } } } catch (Exception e) { MessageBox.Show ("An exception has occurred: " + e.Message, "Error", MessageBoxButtons.OK); Dialogue.Error ("An unhandled exception occurred! " + e.GetType() + ": " + e.Message); } }
private void HandleFile(string folder1, string folder2, Dictionary <string, CompareMode> specialFiles, Dictionary <string, Comparence> comparence, FileInfo file, bool inReference, bool ignoreSame = true) { if (comparence.ContainsKey(file.Name)) { return; } var cd = new Comparence { Name = file.Name, File1FullPath = file.FullName, Result = CompareResult.DoesNotExist, InReference = inReference }; var file2FullName = cd.File1FullPath.Replace(folder1, folder2); if (File.Exists(file2FullName)) { cd.File2FullPath = file2FullName; string contentMarker = null; if (specialFiles != null && specialFiles.Count > 0) { CompareMode specialFileMode; if (specialFiles.TryGetValue(file.Name, out specialFileMode)) { if (specialFileMode == CompareMode.MarkedContent) { contentMarker = Constansts.CONTENT_MARKER; } else { cd.Result = CompareResult.TheSame; return; } } } cd.Result = CompareResult.HasContentDifferences; cd.Difference = AnyDifference(cd.File1FullPath, cd.File2FullPath, contentMarker); if (cd.Difference == null) { if (ignoreSame) { return; } cd.Result = CompareResult.TheSame; } } comparence.Add(file.Name, cd); }
/// <summary> /// Builds an analyzer with the stop words from the given file. </summary> /// <seealso cref="WordlistLoader.GetWordSet(TextReader, LuceneVersion)"/> /// <param name="matchVersion"> See <see cref="LuceneVersion"/> </param> /// <param name="stopwordsFile"> File to load stop words from </param> public StopAnalyzer(LuceneVersion matchVersion, FileInfo stopwordsFile) : this(matchVersion, LoadStopwordSet(stopwordsFile, matchVersion)) { }
/// <summary> /// /// </summary> public void Import() { var foldersCreated = 0; foreach (var inputFile in Directory.GetFiles(_config.Source, "*.*", SearchOption.AllDirectories) .Where(f => f.EndsWith(".jpg", StringComparison.InvariantCultureIgnoreCase) || f.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase) || f.EndsWith(".mp4", StringComparison.InvariantCultureIgnoreCase) || f.EndsWith(".mov", StringComparison.InvariantCultureIgnoreCase)).AsParallel()) { string fileName = new FileInfo(inputFile).Name; DateTime?dateTaken = null; // My Cameras / phones name photos with 2 conventions: // IMG_yyyyMMdd_hhmmss.jpg // yyyyMMdd_hhmmss.jpg // We'll try and pull the date taken from the filename and if not available, fall back to EXIF data // because pulling EXIF data is slow. var fileNameTokens = fileName.Split('_'); if (fileNameTokens.Length > 0) { var dateToken = fileNameTokens[0] == "IMG" ? fileNameTokens[1] : fileNameTokens[0]; if (DateTime.TryParseExact(dateToken, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateTakenFromFileName)) { dateTaken = dateTakenFromFileName; } } if (!dateTaken.HasValue && TryGetDateTakenFromImageProperties(inputFile, out DateTime dateTakenFromImageProperties)) { // Couldn't find date taken from filename - try the exif data dateTaken = dateTakenFromImageProperties; } if (!dateTaken.HasValue) { // Photos could be downloaded images (e.g. synced using IFTTT from facebook etc) dateTaken = File.GetLastWriteTime(inputFile); } // Create destination folder based on the photos date taken in a yyyy-MM/dd structure var outputFolder = Path.Combine( _config.Destination, dateTaken.Value.ToString("yyyy-MM"), dateTaken.Value.ToString("dd")); lock (dirLock) // multiple threads could all try and create the same dir { if (!Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); foldersCreated++; } } var outputFile = Path.Combine(outputFolder, fileName); try { File.Move(inputFile, outputFile); Console.WriteLine("Moved {0} ---> {1}", inputFile, outputFile); } catch (IOException e) { if (e.Message == "Cannot create a file when that file already exists.\r\n") { File.Delete(inputFile); } Console.WriteLine("ERROR {0} ---> {1} :::: {2}", inputFile, outputFile, e.Message); } finally { // If the directory is now empty, then we can delete it to clean up var directoryPath = Path.GetDirectoryName(inputFile); if (!Directory.EnumerateFileSystemEntries(directoryPath).Any(f => f != "Thumbs.db")) { Directory.Delete(directoryPath); } } } Console.WriteLine("Created {0} folders", foldersCreated); Console.ReadLine(); }
public void TakeSnapshot(FileInfo file) { TakeSnapshot(file, 0, 0); }
/// <summary> /// Does the Analysis /// Returns a DataTable /// </summary> /// <param name="fiSegmentOfSourceFile"></param> /// <param name="configDict"></param> /// <param name="diOutputDir"></param> /// <param name="opFileName"></param> /// <param name="segmentStartOffset"></param> /// <param name="config"></param> /// <param name="segmentAudioFile"></param> public static Tuple <BaseSonogram, double[, ], double[], List <AcousticEvent>, TimeSpan> Analysis(FileInfo fiSegmentOfSourceFile, Dictionary <string, string> configDict, DirectoryInfo diOutputDir, string opFileName, TimeSpan segmentStartOffset) { //set default values int bandWidth = 500; //detect bars in bands of this width. int frameSize = 1024; double windowOverlap = 0.0; double intensityThreshold = double.Parse(configDict[key_INTENSITY_THRESHOLD]); //intensityThreshold = 0.01; AudioRecording recording = AudioRecording.GetAudioRecording(fiSegmentOfSourceFile, RESAMPLE_RATE, diOutputDir.FullName, opFileName); if (recording == null) { LoggedConsole.WriteLine("############ WARNING: Recording could not be obtained - likely file does not exist."); return(null); } int sr = recording.SampleRate; double binWidth = recording.SampleRate / (double)frameSize; double frameDuration = frameSize / (double)sr; double frameOffset = frameDuration * (1 - windowOverlap); //seconds between start of each frame double framesPerSecond = 1 / frameOffset; TimeSpan tsRecordingtDuration = recording.Duration; int colStep = (int)Math.Round(bandWidth / binWidth); //i: GET SONOGRAM AS MATRIX double epsilon = Math.Pow(0.5, recording.BitsPerSample - 1); var results2 = DSP_Frames.ExtractEnvelopeAndAmplSpectrogram(recording.WavReader.Samples, sr, epsilon, frameSize, windowOverlap); double[] avAbsolute = results2.Average; //average absolute value over the minute recording //double[] envelope = results2.Item2; double[,] spectrogram = results2.AmplitudeSpectrogram; //amplitude spectrogram. Note that column zero is the DC or average energy value and can be ignored. double windowPower = results2.WindowPower; //############################ NEXT LINE FOR DEBUGGING ONLY //spectrogram = GetTestSpectrogram(spectrogram.GetLength(0), spectrogram.GetLength(1), 0.01, 0.03); var output = DetectGratingEvents(spectrogram, colStep, intensityThreshold); var amplitudeArray = output.Item2; //for debug purposes only //convert List of Dictionary events to List of ACousticevents. //also set up the hits matrix. int rowCount = spectrogram.GetLength(0); int colCount = spectrogram.GetLength(1); var hitsMatrix = new double[rowCount, colCount]; var acousticEvents = new List <AcousticEvent>(); double minFrameCount = 8; //this assumes that the minimum grid is 2 * 4 = 8 long foreach (Dictionary <string, double> item in output.Item1) { int minRow = (int)item[key_START_FRAME]; int maxRow = (int)item[key_END_FRAME]; int frameCount = maxRow - minRow + 1; if (frameCount < minFrameCount) { continue; //only want events that are over a minimum length } int minCol = (int)item[key_MIN_FREQBIN]; int maxCol = (int)item[key_MAX_FREQBIN]; double periodicity = item[key_PERIODICITY]; double[] subarray = DataTools.Subarray(avAbsolute, minRow, maxRow - minRow + 1); double severity = 0.1; int[] bounds = DataTools.Peaks_CropToFirstAndLast(subarray, severity); minRow = minRow + bounds[0]; maxRow = minRow + bounds[1]; if (maxRow >= rowCount) { maxRow = rowCount - 1; } Oblong o = new Oblong(minRow, minCol, maxRow, maxCol); var ae = new AcousticEvent(segmentStartOffset, o, results2.NyquistFreq, frameSize, frameDuration, frameOffset, frameCount); ae.Name = string.Format("p={0:f0}", periodicity); ae.Score = item[key_SCORE]; ae.ScoreNormalised = item[key_SCORE] / 0.5; acousticEvents.Add(ae); //display event on the hits matrix for (int r = minRow; r < maxRow; r++) { for (int c = minCol; c < maxCol; c++) { hitsMatrix[r, c] = periodicity; } } } //foreach //set up the songogram to return. Use the existing amplitude sonogram int bitsPerSample = recording.WavReader.BitsPerSample; //NoiseReductionType nrt = SNR.Key2NoiseReductionType("NONE"); NoiseReductionType nrt = SNR.KeyToNoiseReductionType("STANDARD"); var sonogram = (BaseSonogram)SpectrogramStandard.GetSpectralSonogram(recording.BaseName, frameSize, windowOverlap, bitsPerSample, windowPower, sr, tsRecordingtDuration, nrt, spectrogram); sonogram.DecibelsNormalised = new double[sonogram.FrameCount]; for (int i = 0; i < sonogram.FrameCount; i++) //foreach frame or time step { sonogram.DecibelsNormalised[i] = 2 * Math.Log10(avAbsolute[i]); } sonogram.DecibelsNormalised = DataTools.normalise(sonogram.DecibelsNormalised); return(Tuple.Create(sonogram, hitsMatrix, amplitudeArray, acousticEvents, tsRecordingtDuration)); } //Analysis()
protected abstract bool FoundFileOnDiskForFileInTorrent(string torrentFile, FileInfo onDisk, int numberInTorrent, string nameInTorrent);
public void TakeSnapshot(FileInfo file, uint width, uint height) { Manager.TakeSnapshot(myMediaPlayerInstance, file, width, height); }
/// <summary> /// 为脚本文件设置临时数据库文件 /// </summary> /// <param name="bitFile"></param> public static void Use(string bitFile) { FileInfo file = new FileInfo(bitFile); DirectoryInfo rootDir = file.Directory.Parent; AppSettings.Instance.CurrentExecutePath = rootDir.FullName; }
public VlcMedia SetMedia(FileInfo file, params string[] options) { return SetMedia(new VlcMedia(this, file, options)); }
public static bool IsFile(FileInfo file) => VoteFilePattern.IsMatch(file.Name);
public bool ProcessTorrentFile(string torrentFile, TreeView tvTree, CommandLineArgs args) { // ---------------------------------------- // read in torrent file if (tvTree != null) { tvTree.Nodes.Clear(); } BEncodeLoader bel = new BEncodeLoader(); BTFile btFile = bel.Load(torrentFile); if (btFile is null) { return(false); } BTItem bti = btFile.GetItem("info"); if ((bti is null) || (bti.Type != BTChunk.kDictionary)) { return(false); } BTDictionary infoDict = (BTDictionary)(bti); bti = infoDict.GetItem("piece length"); if ((bti is null) || (bti.Type != BTChunk.kInteger)) { return(false); } long pieceSize = ((BTInteger)bti).Value; bti = infoDict.GetItem("pieces"); if ((bti is null) || (bti.Type != BTChunk.kString)) { return(false); } BTString torrentPieces = (BTString)(bti); bti = infoDict.GetItem("files"); if (bti is null) // single file torrent { bti = infoDict.GetItem("name"); if ((bti is null) || (bti.Type != BTChunk.kString)) { return(false); } BTString di = (BTString)(bti); string nameInTorrent = di.AsString(); BTItem fileSizeI = infoDict.GetItem("length"); long fileSize = ((BTInteger)fileSizeI).Value; NewTorrentEntry(torrentFile, -1); if (DoHashChecking) { byte[] torrentPieceHash = torrentPieces.StringTwentyBytePiece(0); FileInfo fi = FindLocalFileWithHashAt(torrentPieceHash, 0, pieceSize, fileSize); if (fi != null) { FoundFileOnDiskForFileInTorrent(torrentFile, fi, -1, nameInTorrent); } else { DidNotFindFileOnDiskForFileInTorrent(torrentFile, -1, nameInTorrent); } } FinishedTorrentEntry(torrentFile, -1, nameInTorrent); // don't worry about updating overallPosition as this is the only file in the torrent } else { long overallPosition = 0; long lastPieceLeftover = 0; if (bti.Type != BTChunk.kList) { return(false); } BTList fileList = (BTList)(bti); // list of dictionaries for (int i = 0; i < fileList.Items.Count; i++) { Prog(100 * i / fileList.Items.Count, i.ToString()); if (fileList.Items[i].Type != BTChunk.kDictionary) { return(false); } BTDictionary file = (BTDictionary)(fileList.Items[i]); BTItem thePath = file.GetItem("path"); if (thePath.Type != BTChunk.kList) { return(false); } BTList pathList = (BTList)(thePath); // want the last of the items in the list, which is the filename itself int n = pathList.Items.Count - 1; if (n < 0) { return(false); } BTString fileName = (BTString)(pathList.Items[n]); BTItem fileSizeI = file.GetItem("length"); long fileSize = ((BTInteger)fileSizeI).Value; int pieceNum = (int)(overallPosition / pieceSize); if (overallPosition % pieceSize != 0) { pieceNum++; } NewTorrentEntry(torrentFile, i); if (DoHashChecking) { byte[] torrentPieceHash = torrentPieces.StringTwentyBytePiece(pieceNum); FileInfo fi = FindLocalFileWithHashAt(torrentPieceHash, lastPieceLeftover, pieceSize, fileSize); if (fi != null) { FoundFileOnDiskForFileInTorrent(torrentFile, fi, i, fileName.AsString()); } else { DidNotFindFileOnDiskForFileInTorrent(torrentFile, i, fileName.AsString()); } } FinishedTorrentEntry(torrentFile, i, fileName.AsString()); int sizeInPieces = (int)(fileSize / pieceSize); if (fileSize % pieceSize != 0) { sizeInPieces++; // another partial piece } lastPieceLeftover = (lastPieceLeftover + (int)((sizeInPieces * pieceSize) - fileSize)) % pieceSize; overallPosition += fileSize; } // for each file in the torrent } if (tvTree != null) { tvTree.BeginUpdate(); btFile.Tree(tvTree.Nodes); tvTree.ExpandAll(); tvTree.EndUpdate(); tvTree.Update(); } Prog(0, string.Empty); return(true); }
public async Task <List <string> > ExpandModel(FileInfo modelFile) { string dtmi = ParsingUtils.GetRootId(modelFile); return(await ExpandModel(dtmi)); }
/// <summary> /// 저널파일 FTP 전송 /// </summary> /// <returns></returns> private bool SetFTP() { bool bReturn = false; string strFtpMsg = string.Empty; SetMsgBar(osiMsgBar04, OpenItemStatus.None, strMsg16); try { string strServer = ConfigData.Current.AppConfig.PosFTP.FtpSvrIP1; string strUser = ConfigData.Current.AppConfig.PosFTP.User; string strPass = ConfigData.Current.AppConfig.PosFTP.Pass; string strPort = ConfigData.Current.AppConfig.PosFTP.FtpComPort1; string strPath = Path.Combine( FXConsts.JOURNAL.GetFolder(), string.Format("{0}-{1}-{2}.jrn", ConfigData.Current.AppConfig.PosInfo.SaleDate, ConfigData.Current.AppConfig.PosInfo.StoreNo, ConfigData.Current.AppConfig.PosInfo.PosNo) ); FileInfo fi = new FileInfo(strPath); if (fi.Exists) { if (strServer.Length > 0 && strUser.Length > 0 && strPass.Length > 0 && strPort.Length > 0 && strPath.Length > 0) { FtpUtils ftp = new FtpUtils(strServer, strUser, strPass, 10, TypeHelper.ToInt32(strPort)); if (ftp.Login(out strFtpMsg)) { //폴더 검사 string[] arrDir = ftp.GetFileList(string.Format("{0}", ConfigData.Current.AppConfig.PosFTP.JournalPath), out bReturn, out strFtpMsg); if (bReturn) { if (arrDir.Length > 0) { string strDir = string.Format("{0}/{1}", ConfigData.Current.AppConfig.PosFTP.JournalPath, ConfigData.Current.AppConfig.PosInfo.SaleDate); bool bMake = false; foreach (string strTemp in arrDir) { if (strTemp == strDir) { bMake = true; break; } } if (bMake) { //폴더존재시 이동 bReturn = ftp.ChangeDir(strDir, out strFtpMsg); } else { bReturn = ftp.MakeDir(strDir, out strFtpMsg); } } } } if (bReturn) { for (int i = 0; i < 3; i++) { if (ftp.Upload(strPath, out strFtpMsg)) { ftp.Close(); bReturn = true; break; } } } } } else { bReturn = true; } if (!bReturn) { string[] strBtnNm = new string[1]; strBtnNm[0] = WSWD.WmallPos.FX.Shared.ConfigData.Current.SysMessage.GetMessage("00045"); //strBtnNm[1] = WSWD.WmallPos.FX.Shared.ConfigData.Current.SysMessage.GetMessage("00190"); //LogUtils.Instance.LogException(strFtpMsg); //if (ShowMessageBox(MessageDialogType.Warning, null, strMsg22, strBtnNm) == DialogResult.Yes) //{ //} ShowMessageBox(MessageDialogType.Warning, null, strMsg22, strBtnNm); #if DEBUG m_ftpFailedCount++; if (m_ftpFailedCount >= MAX_FTP_COUNT) { bReturn = true; } else { bReturn = SetFTP(); } #else bReturn = SetFTP(); #endif //else //{ // bReturn = false; // //ChildManager.ShowProgress(false); // //SetControlDisable(false); // ////화면 종료 // //this.DialogResult = DialogResult.Cancel; // //if (!_bAuto) // //{ // // //시스템 종료 // // InitiateSystemShutdown("\\\\127.0.0.1", null, 0, false, false); // //} //} } } catch (Exception ex) { LogUtils.Instance.LogException(ex); } finally { SetMsgBar(osiMsgBar04, bReturn ? OpenItemStatus.OK : OpenItemStatus.Error, bReturn ? strMsg17 : strMsg18); } return(bReturn); }
public void Show() { Data_Emp = new Dictionary <string, Employer>(); FileInfo fi2 = new FileInfo("emps.dat"); FileInfo fi3 = new FileInfo("pers.xml"); if (fi2.Exists | fi3.Exists) { if (Config == "binary") { BinaryFormatter bf2 = new BinaryFormatter(); using (FileStream fs = new FileStream("emps.dat", FileMode.Open)) { Dictionary <string, Employer> data = new Dictionary <string, Employer>(); data = (Dictionary <string, Employer>)bf2.Deserialize(fs); Data_Emp = data; } } else if (Config == "xml") { // XmlSerializer xs_2 = new XmlSerializer(typeof(Dictionary<string, Employer>)); // using (FileStream fs_2 = new FileStream("emps.xml", FileMode.OpenOrCreate)) // { // Dictionary<string, Employer> data_xml = new Dictionary<string, Employer>(); // xs_2.Serialize(fs_2, data_xml); // } } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("В конфигурационном файле option.ini указаны некорректные данные - {0}", Config); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("Выполняется запись по умолчанию (binary) в конфигурационный файл option.ini..."); Thread.Sleep(2000); using (FileStream fstream2 = new FileStream("option.ini", FileMode.Truncate)) { string text = "binary"; byte[] array = Encoding.Default.GetBytes(text); fstream2.Write(array, 0, array.Length); } Console.WriteLine("Конфигурационные данные перезаписаны!"); Console.ResetColor(); Show(); } } else { Console.WriteLine("Отсутвует файл для десеарилации emps.dat или pers.xml. Данные с последнего сеанса не загружены!\n"); } while (true) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("\nКол-во сотрудников в базе: {0}", Data_Emp.Count); Console.ResetColor(); Console.WriteLine("\nБаза данных о сотрудниках фирмы\n"); Console.Write("Введите команду: "); try { string command = Console.ReadLine(); Console.Clear(); switch (command.ToLower()) { case "add": Console.WriteLine("Введите уникальный № ID:"); string id2 = Console.ReadLine(); Console.WriteLine("Введите имя:"); string name2 = Console.ReadLine(); Console.WriteLine("Введите возраст:"); int age2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Введите название фирмы:"); string company2 = Console.ReadLine(); Console.WriteLine("Введите должность:"); string post2 = Console.ReadLine(); Data_Emp.Add(id2, new Employer(name2, age2, company2, post2)); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("\nДобавлена запись"); ShowInfo_ID(id2); Thread.Sleep(2000); Console.ResetColor(); Console.Clear(); break; case "info": Console.Clear(); Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("\nВыполнение запроса..."); Thread.Sleep(1100); Console.Clear(); ShowInfo(); Console.ResetColor(); break; case "del": Console.Clear(); ShowInfo(); Console.WriteLine("\nВведите ID для удаления:"); string num = Console.ReadLine(); Data_Emp.Remove(num); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("ID {0} удалена из списка", num); Console.ResetColor(); break; case "info_id": foreach (KeyValuePair <string, Employer> p in Data_Emp) { Console.ForegroundColor = ConsoleColor.Magenta; Console.Write("id " + p.Key + " - "); Console.ResetColor(); Console.WriteLine(p.Value.Post); } Console.WriteLine("\nВведите ID сотрудника:"); string id3 = Console.ReadLine(); ShowInfo_ID(id3); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\nКоманда выполнена"); Console.ResetColor(); break; default: Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("\nДоступные команды:\n \nadd - добавить запись \ndel - удалить запись "); Console.WriteLine("info - посмотреть записи о всех сотрудниках \ninfo_id - посмотреть запись о конктретном сотруднике"); Console.WriteLine("exit - выйти из программы. Данные сохранятся автоматически"); Console.WriteLine("exit* - выйти из программы без сохранения"); Console.ResetColor(); break; case "exit": Dictionary <string, Employer> empl_2 = new Dictionary <string, Employer> (); empl_2 = /*employers*/ Data_Emp; if (Config == "binary") { BinaryFormatter bf = new BinaryFormatter(); using (FileStream fs = new FileStream("emps.dat", FileMode.OpenOrCreate)) { bf.Serialize(fs, empl_2); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Данные сохранены (сериализованы через BinaryFormatter)"); Console.WriteLine("Сеанс окончен! До свидания!\n"); } } else if (Config == "xml") { XmlSerializer xs = new XmlSerializer(typeof(Dictionary <string, Employer>)); using (FileStream fs_2 = new FileStream("pers.xml", FileMode.OpenOrCreate)) { xs.Serialize(fs_2, empl_2); Console.WriteLine("Данные сохранены (сериализованы через XmlSerializer)"); Console.WriteLine("Сеанс окончен! До свидания!\n"); } } return; case "exit*": Console.WriteLine("Сеанс окончен! До свидания!\n"); return; } } catch (Exception e) { Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("Ошибка ввода \n" + e); Console.ResetColor(); } } }
/// <summary> /// Extract an entry from the archive. This method assumes that the /// tarIn stream has been properly set with a call to GetNextEntry(). /// </summary> /// <param name="destDir"> /// The destination directory into which to extract. /// </param> /// <param name="entry"> /// The TarEntry returned by tarIn.GetNextEntry(). /// </param> void ExtractEntry(string destDir, TarEntry entry) { OnProgressMessageEvent(entry, null); string name = entry.Name; if (Path.IsPathRooted(name) == true) { // NOTE: // for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt name = name.Substring(Path.GetPathRoot(name).Length); } name = name.Replace('/', Path.DirectorySeparatorChar); string destFile = Path.Combine(destDir, name); if (entry.IsDirectory) { EnsureDirectoryExists(destFile); } else { string parentDirectory = Path.GetDirectoryName(destFile); EnsureDirectoryExists(parentDirectory); bool process = true; FileInfo fileInfo = new FileInfo(destFile); if (fileInfo.Exists) { if (this.keepOldFiles) { OnProgressMessageEvent(entry, "Destination file already exists"); process = false; } else if ((fileInfo.Attributes & FileAttributes.ReadOnly) != 0) { OnProgressMessageEvent(entry, "Destination file already exists, and is read-only"); process = false; } } if (process) { bool asciiTrans = false; Stream outputStream = File.Create(destFile); if (this.asciiTranslate) { asciiTrans = !IsBinary(destFile); } StreamWriter outw = null; if (asciiTrans) { outw = new StreamWriter(outputStream); } byte[] rdbuf = new byte[32 * 1024]; while (true) { int numRead = this.tarIn.Read(rdbuf, 0, rdbuf.Length); if (numRead <= 0) { break; } if (asciiTrans) { for (int off = 0, b = 0; b < numRead; ++b) { if (rdbuf[b] == 10) { string s = Encoding.ASCII.GetString(rdbuf, off, (b - off)); outw.WriteLine(s); off = b + 1; } } } else { outputStream.Write(rdbuf, 0, numRead); } } if (asciiTrans) { outw.Close(); } else { outputStream.Close(); } } } }
/// <summary> /// Gets the item image infos. /// </summary> /// <param name="item">The item.</param> /// <returns>Task{List{ImageInfo}}.</returns> public async Task<List<ImageInfo>> GetItemImageInfos(BaseItem item) { var list = new List<ImageInfo>(); foreach (var image in item.Images) { var path = image.Value; var fileInfo = new FileInfo(path); var dateModified = Kernel.Instance.ImageManager.GetImageDateModified(item, path); var size = await Kernel.Instance.ImageManager.GetImageSize(path, dateModified).ConfigureAwait(false); list.Add(new ImageInfo { Path = path, ImageType = image.Key, ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, image.Key, path), Size = fileInfo.Length, Width = Convert.ToInt32(size.Width), Height = Convert.ToInt32(size.Height) }); } var index = 0; foreach (var image in item.BackdropImagePaths) { var fileInfo = new FileInfo(image); var dateModified = Kernel.Instance.ImageManager.GetImageDateModified(item, image); var size = await Kernel.Instance.ImageManager.GetImageSize(image, dateModified).ConfigureAwait(false); list.Add(new ImageInfo { Path = image, ImageIndex = index, ImageType = ImageType.Backdrop, ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Backdrop, image), Size = fileInfo.Length, Width = Convert.ToInt32(size.Width), Height = Convert.ToInt32(size.Height) }); index++; } index = 0; foreach (var image in item.ScreenshotImagePaths) { var fileInfo = new FileInfo(image); var dateModified = Kernel.Instance.ImageManager.GetImageDateModified(item, image); var size = await Kernel.Instance.ImageManager.GetImageSize(image, dateModified).ConfigureAwait(false); list.Add(new ImageInfo { Path = image, ImageIndex = index, ImageType = ImageType.Screenshot, ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Screenshot, image), Size = fileInfo.Length, Width = Convert.ToInt32(size.Width), Height = Convert.ToInt32(size.Height) }); index++; } var video = item as Video; if (video != null) { index = 0; foreach (var chapter in _itemRepo.GetChapters(video.Id)) { if (!string.IsNullOrEmpty(chapter.ImagePath)) { var image = chapter.ImagePath; var fileInfo = new FileInfo(image); var dateModified = Kernel.Instance.ImageManager.GetImageDateModified(item, image); var size = await Kernel.Instance.ImageManager.GetImageSize(image, dateModified).ConfigureAwait(false); list.Add(new ImageInfo { Path = image, ImageIndex = index, ImageType = ImageType.Chapter, ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Chapter, image), Size = fileInfo.Length, Width = Convert.ToInt32(size.Width), Height = Convert.ToInt32(size.Height) }); } index++; } } return list; }
private void DoWork(object data) { var tuple = (Tuple <string, string, bool, bool, int?, bool>)data; var srcDir = tuple.Item1; var tgtDir = tuple.Item2; var isWCacheOn = tuple.Item3; var isRcacheOn = tuple.Item4; var count = tuple.Item5; var isAutoExit = tuple.Item6; var MyCounter = MakeCounter(); var files = Directory.GetFiles(srcDir); while (true) { this.Invoke(new Action(() => lbCount.Text = MyCounter().ToString())); foreach (var file in files) { var srcFileInfo = new FileInfo(file); var tgtFileInfo = new FileInfo(Path.Combine(tgtDir, srcFileInfo.Name)); try { #region COPY // update status to copy this.Invoke(new Action(() => tbStatusInfo.Text = TM.Translate("copy:") + srcFileInfo.Name)); // copy using (var readStream = new FileStream(srcFileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare. ReadWrite, 4096, isRcacheOn ? FileOptions.None : (FileOptions)0x20000000)) using (var writeStream = new FileStream(tgtFileInfo.FullName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, 4096, isWCacheOn ? FileOptions.None : FileOptions.WriteThrough)) { int c = -1; long bytes = 0; while ((c = readStream.ReadByte()) != -1) { writeStream.WriteByte((byte)c); // show copy progress when file is greater than 200MB if (++bytes % (1024 * 1024) == 0 && readStream.Length > 1024 * 1024 * 200) { var length = readStream.Length; this.BeginInvoke(new Action(() => UpdateAppStatus("copied:", string.Format("{0:d}M / {1:d}M", bytes / 1024 / 1024, length / 1024 / 1024), false))); } } // clean app status this.Invoke(new Action(() => lbStatus.Text = "")); } #endregion #region COMPARE // update status to compare this.Invoke(new Action(() => tbStatusInfo.Text = TM.Translate("compare:") + srcFileInfo.Name)); // compare CompareMd5(srcFileInfo, tgtFileInfo); #endregion #region DELETE // update status to delete this.Invoke(new Action(() => tbStatusInfo.Text = TM.Translate("delete:") + srcFileInfo.Name)); // delete tgtFileInfo.Delete(); } catch (ThreadAbortException) { return; } catch (Exception e) { // raise the error messagebox at main thread to block the UI (Modal) if ((bool)this.Invoke(new Func <bool>(() => AskWhetherContinue(e.Message)))) { continue; } else { // prepare ending this thread this.Invoke(new Action(() => this.UpdateControls(WorkState.WaitingStartForcely))); return; } } #endregion } // since count is nullable type following is necessary // if (count == null) continue; count--; if (count == 0) { break; } } // prepare ending this thread this.Invoke(new Action(() => elapsedTimer.Stop())); this.Invoke(new Action(() => this.UpdateControls(WorkState.WaitingStart))); // end main thread if necessary // COMMENT // Invoke method is blocking. If the working thread is foreground, // following code fails (different to BeginInvoke() method) if (isAutoExit) { this.Invoke(new Action(() => this.UpdateAppStatus("app_info_1"))); this.BeginInvoke(new Action(() => this.exitTimer.Start())); } }
private void ProcessJob(JobInfo jobInfo) { // Debug.LogFormat("processing job: {0} ({1})", jobInfo.name, jobInfo.comment); var tempPath = jobInfo.path + PartExt; if (_fileStream != null) { _fileStream.Close(); _fileStream = null; } var dataChecker = GetDataChecker(jobInfo); while (true) { string error = null; var partialSize = 0; var success = true; var wsize = jobInfo.size; var wchecksum = jobInfo.checksum; var url = GetUrl(jobInfo); dataChecker.Reset(); if (_fileStream == null) { try { var fileInfo = new FileInfo(tempPath); if (fileInfo.Exists) // 处理续传 { _fileStream = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite); partialSize = (int)fileInfo.Length; if (partialSize > jobInfo.size) // 目标文件超过期望大小, 直接废弃 { _fileStream.SetLength(0); partialSize = 0; } else if (partialSize <= jobInfo.size) // 续传 { dataChecker.Update(_fileStream); // Debug.LogFormat("partial check {0} && {1} ({2})", partialSize, jobInfo.size, // dataChecker.hex); } } else // 创建下载文件 { if (!Directory.Exists(fileInfo.DirectoryName)) { Directory.CreateDirectory(fileInfo.DirectoryName); } _fileStream = File.Open(tempPath, FileMode.OpenOrCreate, FileAccess.ReadWrite); _fileStream.SetLength(0); } } catch (Exception exception) { // ResourceManager.logger.OnTaskError(jobInfo, exception); error = string.Format("file exception: {0}", exception); success = false; } } else { _fileStream.SetLength(0L); } if (success && (jobInfo.size <= 0 || partialSize < jobInfo.size)) { try { var uri = new Uri(url); var req = WebRequest.CreateHttp(uri); req.Method = WebRequestMethods.Http.Get; req.ContentType = BundleContentType; // req.ReadWriteTimeout = 10000; if (_timeout > 0) { req.Timeout = _timeout; } if (partialSize > 0) { req.AddRange(partialSize); } using (var rsp = req.GetResponse()) { using (var webStream = rsp.GetResponseStream()) { var recvAll = 0L; var recvCalc = 0L; var stopwatch = new Stopwatch(); stopwatch.Start(); while (recvAll < rsp.ContentLength) { var _bpms = Math.Max(1, jobInfo.bytesPerSecond / 10); var recv = webStream.Read(_buffer, 0, Math.Min(_bpms, _buffer.Length)); if (recv > 0 && !_destroy) { recvCalc += recv; if (recvCalc >= _bpms) { var millisecs = stopwatch.ElapsedMilliseconds; var delay = (int)(100.0 * recvCalc / _bpms - millisecs); // Debug.LogFormat("net ++ {0} {1} sbps {2} recv {3}", delay, millisecs, _bpms, recvCalc); if (delay > 0) { Thread.Sleep(delay); } stopwatch.Restart(); recvCalc -= _bpms; } recvAll += recv; _fileStream.Write(_buffer, 0, recv); dataChecker.Update(_buffer, 0, recv); jobInfo.bytes = (int)(recvAll + partialSize); // PrintDebug($"{recvAll + partialSize}, {_size}, {_progress}"); } else { break; } } } } } catch (Exception exception) { // ResourceManager.logger.OnTaskError(jobInfo, exception); // Debug.LogErrorFormat("network exception: {0}\n{1}", url, exception); error = string.Format("network exception: {0}", exception); success = false; } } if (success && _fileStream.Length != jobInfo.size) { if (jobInfo.size > 0) { error = string.Format("filesize exception: {0} != {1}", _fileStream.Length, jobInfo.size); // Debug.LogError(error); // ResourceManager.logger.OnTaskError(jobInfo, error); success = false; } else { wsize = (int)_fileStream.Length; } } if (success) { // dirty code, md5 目前不能分段计算 if (dataChecker.hex == null) { _fileStream.Seek(0, SeekOrigin.Begin); dataChecker.ComputeHashFull(_fileStream); } if (dataChecker.hex != jobInfo.checksum) { if (!string.IsNullOrEmpty(jobInfo.checksum)) { error = string.Format("corrupted file: {0} != {1}", dataChecker.hex, jobInfo.checksum); // Debug.LogError(error); // ResourceManager.logger.OnTaskError(jobInfo, error); success = false; } else { wchecksum = dataChecker.hex; } } } if (_destroy) { success = false; } // close fileStream anyway try { if (_fileStream != null) { _fileStream.Close(); _fileStream = null; } } catch (Exception) { } if (success) { try { // _WriteStream(buffer, fileStream, finalPath); if (File.Exists(jobInfo.path)) { File.Delete(jobInfo.path); } File.Move(tempPath, jobInfo.path); // 写入额外的 meta var meta = new Metadata() { checksum = wchecksum, size = wsize, }; var json = JsonUtility.ToJson(meta); var metaPath = jobInfo.path + Metadata.Ext; File.WriteAllText(metaPath, json); Complete(jobInfo); break; } catch (Exception exception) { error = string.Format("write exception: {0}", exception); // Debug.LogError(error); // ResourceManager.logger.OnTaskError(jobInfo, error); success = false; } } jobInfo.tried++; if (jobInfo.retry > 0 && jobInfo.tried >= jobInfo.retry) { jobInfo.error = error ?? "unknown error"; Complete(jobInfo); break; } ResourceManager.logger.OnTaskError(jobInfo, error); Thread.Sleep(1000); // Debug.LogErrorFormat("[retry] download failed: {0}\n{1}", url, error); } }
protected abstract IEnumerable <TVolume> LoadVolumes(FileInfo file);