private static FileStruct ParseFileStructFromUnixStyleRecord(string Record) { GF.doDebug(Record); ///Assuming record style as /// dr-xr-xr-x 1 owner group 0 Nov 25 2002 bussys FileStruct f = new FileStruct(); string processstr = Record.Trim(); f.Flags = processstr.Substring(0, 9); f.IsDirectory = (f.Flags[0] == 'd'); processstr = (processstr.Substring(11)).Trim(); _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //skip one part f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); f.Group = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); f.Size = Convert.ToInt64(_cutSubstringFromStringWithTrim(ref processstr, ' ', 0)); //_cutSubstringFromStringWithTrim(ref processstr,' ',0); //skip one part f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', 8)); f.Name = processstr; //Rest of the part is name return(f); }
public async Task <GF> PrepareGFByTGAName(string tgaName) { FileStruct file = fileList.FirstOrDefault(f => f.TGAName.ToLower().Replace('/', '\\').Equals(tgaName.ToLower().Replace('/', '\\'))); if (file == null) { return(null); } Reader reader = readers[file.fileNum]; PartialHttpStream httpStream = reader.BaseStream as PartialHttpStream; if (httpStream != null) { Controller c = MapLoader.Loader.controller; readers[file.fileNum].BaseStream.Seek(file.pointer, SeekOrigin.Begin); await httpStream.FillCacheForRead(file.size); } byte[] bytes = GetFileBytes(file); //Util.ByteArrayToFile("textures/" + file.FullName, bytes); return(new GF(bytes)); }
public Main(int userId) { try { _userActive = DataMethod.GetUser(userId); } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } _statusFile = StatusFileEnum.My; _fileStruct = new FileStruct(); InitializeComponent(); Icon = Properties.Resources.box; ButtonActive(buttonMyFiles); FillTable(); FillForm(); }
/// <summary> /// 从Unix格式中返回文件信息 /// </summary> /// <param name="Record">文件信息</param> private FileStruct ParseFileStructFromUnixStyleRecord(string Record) { FileStruct f = new FileStruct(); string processstr = Record.Trim(); f.Flags = processstr.Substring(0, 10); f.IsDirectory = (f.Flags[0] == 'd'); processstr = (processstr.Substring(11)).Trim(); _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //跳过一部分 f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); f.Group = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //跳过一部分 string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2]; if (yearOrTime.IndexOf(":") >= 0) //time { processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString()); } f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', 8)); f.Name = processstr; //最后就是名称 return(f); }
public byte[] GetFileBytes(FileStruct file) { if (file == null) { return(null); } readers[file.fileNum].BaseStream.Position = file.pointer; byte[] data = new byte[file.size]; readers[file.fileNum].Read(data, 0, data.Length); for (int i = 0; i < file.size; i++) { if ((file.size % 4) + i < file.size) { data[i] = (byte)(data[i] ^ file.xorKey[i % 4]); } } //MonoBehaviour.print(file.pointer + " - " + file.magic2 + " - " + file.name + " - " + data.Length); return(data); }
/// <summary> /// 运行时调用(忽删除) /// </summary> /// <param name="title"></param> /// <param name="defultName"></param> /// <param name="path"></param> /// <param name="filter"></param> /// <returns></returns> public static string OpenFileDialog(string title, string path, string filter) { FileStruct ofn = new FileStruct(); ofn.structSize = Marshal.SizeOf(ofn); ofn.filter = filter; ofn.file = new string(new char[256]); ofn.maxFile = ofn.file.Length; ofn.fileTitle = new string(new char[64]); ofn.maxFileTitle = ofn.fileTitle.Length; if (!string.IsNullOrEmpty(path)) { path = path.Replace('/', '\\'); } //默认路径 ofn.initialDir = path; ofn.title = title; //显示文件的类型 ofn.defExt = ""; //注意 一下项目不一定要全选 但是0x00000008项不要缺少 ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;//OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR try { if (GetOpenFileName(ofn)) { var filePath = ofn.file.Replace("\0", ""); return(filePath); } else { return(null); } } catch (Exception) { return(null); } }
public void fopen_emptyfile_read_verifyeof() { //Reset State Reset(); var filePath = CreateTextFile("file.txt", string.Empty); var filep = fopen("file.txt", "rb"); Assert.NotEqual(0, filep.Segment); Assert.NotEqual(0, filep.Offset); var memoryStream = new MemoryStream(); var dstBuf = mbbsEmuMemoryCore.AllocateVariable(null, 4096); var elementsRead = fread(dstBuf, 1, 128, filep); Assert.Equal(0, elementsRead); var filepStruct = new FileStruct(mbbsEmuMemoryCore.GetArray(filep, FileStruct.Size)); Assert.True(filepStruct.flags.IsFlagSet((ushort)FileStruct.EnumFileFlags.EOF)); }
public void AddFile(FileStruct file) { string command = string.Format("INSERT INTO excel_files(id, uid, path, name, type, extention)" + "VALUES('{0}', @uid, '{1}', '{2}', '{3}', '{4}');", file.ID, file.Path, file.Name, file.Type, file.Extention); lock (locker) { using (MySqlCommand commandSQL = new MySqlCommand(command, connection)) { if (file.UID == -1) { commandSQL.Parameters.AddWithValue("@uid", null); } else { commandSQL.Parameters.AddWithValue("@uid", file.UID); } commandSQL.ExecuteNonQuery(); commandSQL.Dispose(); } } }
public string AddXls(ref string request, ref byte[] buffer, ref int bytes, ref Socket handleSocket) { FileStruct file = loaderFile.AddFile(ref request, ref buffer, ref bytes); if (file != null) { if (database.upload.CheckUploadExist(ref file.Name)) { logger.WriteLog("Program did not handle this archive, because had finded the same file name in database", LogLevel.Exceling); SendErrorJsonRequest(JsonAnswer(false, "Program did not handle this archive, because had finded the same file name in database"), handleSocket); return(null); } Thread thread = new Thread(() => excelModule.HandleXlsFile(ref file)); thread.IsBackground = true; thread.Start(); return(JsonAnswer(true, "Send xls-file is okay. Server handle info from it")); } else { SendErrorJsonRequest(JsonAnswer(false, "Can not get file from request"), handleSocket); return(null); } }
public byte[] GetFileBytes(string filename) { FileStruct file = fileList.FirstOrDefault(f => (f.directory + "\\" + f.name) == filename); if (file == null) { throw new FileNotFoundException($"{filename} could not be found!"); } r.BaseStream.Position = file.pointer; byte[] data = new byte[file.size]; r.Read(data, 0, data.Length); for (int i = 0; i < file.size; i++) { if ((file.size % 4) + i < file.size) { data[i] = (byte)(data[i] ^ file.xorKey[i % 4]); } } return(data); }
/// <summary> /// Отправляет указанный файл на сервер. /// </summary> /// <param name="fileName">Имя отправляемого файла.</param> void SendFile(string fileName) { // Получаем информацию о файле. var fileInfo = new FileInfo(fileName); Console.WriteLine("Sending the file {0}", fileInfo.Name + " " + fileInfo.Length); // Инстанцируем класс FileStruct описывающий структуру файла для отправки (Имя/Размер). var fileStruct = new FileStruct(GetFilePath(fileInfo.FullName), fileInfo.Length); // Инстанцируем класс BinaryFormatter, который будем использовать для бинарной сериализации объекта. var binaryFormatter = new BinaryFormatter(); // Сериализируем объект в поток NetStream. binaryFormatter.Serialize(netStream, fileStruct); // Получаем поток на чтение файла. fileStream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); // Буфер хранимый данные для отправки. byte[] temp = new byte[BUF_SIZE]; // Кол-во считанных байт. int readBytes = 0; // Цикл отправки файла по сети. // Считываем данные c открытого файла в временный буфер и отправляем их до того момента // пока не считаем все данные. while ((readBytes = fileStream.Read(temp, 0, temp.Length)) > 0) { // Записываем данные в поток NetStream (передаем на сервер). netStream.Write(temp, 0, readBytes); } // Закрываем поток чтения файла. fileStream.Close(); }
public GF GetGF(string filename) { FileStruct file = fileList.FirstOrDefault(f => f.FullName == filename); return(GetGF(file)); }
public static long Length(this FileStruct fileInformat) { return(BitConverter.ToInt32(fileInformat.LengthBytes, 0)); }
public static long Offset(this FileStruct fileInformat) { return(BitConverter.ToInt32(fileInformat.OffsetBytes, 0)); }
private bool update_entorder(FileStruct fs, string directory, string contractno) { string sql = string.Empty; bool content = false; #region try { string enterprisecode = string.Empty; string enterprisename = string.Empty;//待修改 string entid = string.Empty; int start = fs.Name.LastIndexOf("_"); int end = fs.Name.LastIndexOf("."); string suffix = fs.Name.Substring(end + 1, 3).ToUpper();//文件扩展名 string filetype = fs.Name.Substring(start + 1, end - start - 1).ToUpper(); int filetypeid = 0; switch (filetype) { case "CONTRACT": filetypeid = 50; break; case "INVOICE": filetypeid = 51; break; case "PACKING": filetypeid = 52; break; case "SHEET": filetypeid = 44; break; default: filetypeid = 50; break; } sql = "select * from ent_order where code='" + contractno + "' and ENTERPRISECODE='" + enterprisecode + "'"; DataTable dt_ent = DBMgr.GetDataTable(sql); if (dt_ent.Rows.Count == 0) { sql = "select ENT_ORDER_ID.Nextval from dual"; entid = DBMgr.GetDataTable(sql).Rows[0][0] + ""; // sql = @"insert into ent_order(ID,CODE,CREATETIME,SUBMITTIME,UNITCODE,ENTERPRISECODE,ENTERPRISENAME,FILEDECLAREUNITCODE,FILEDECLAREUNITNAME, // FILERECEVIEUNITCODE,FILERECEVIEUNITNAME,TEMPLATENAME,CUSTOMDISTRICTCODE,CUSTOMDISTRICTNAME) VALUES // ('{3}','{0}',sysdate,sysdate,(select fun_AutoQYBH(sysdate) from dual),'{1}','{2}','{4}','{5}','{6}','{7}','COMPAL01','2369','昆山综保')"; // sql = string.Format(sql, contractno, enterprisecode, enterprisename, entid, "3223980002", "江苏飞力达国际物流股份有限公司", "3223980002", "江苏飞力达国际物流股份有限公司"); // DBMgr.ExecuteNonQuery(sql); } else { entid = dt_ent.Rows[0]["ID"] + ""; } //写入随附文件表 sql = @"select * from list_attachment where originalname='" + fs.Name + "' and entid='" + entid + "'"; DataTable dt_att = DBMgr.GetDataTable(sql);//因为客户有可能会重复传文件,此是表记录不需要变化,替换文件即可 if (dt_att.Rows.Count > 0) { sql = "delete from list_attachment where id='" + dt_att.Rows[0]["ID"] + "'"; DBMgr.ExecuteNonQuery(sql); } //dt_att = DBMgr.GetDataTable("select LIST_ATTACHMENT_ID.Nextval ATTACHMENTID from dual"); sql = @"insert into list_attachment(ID,FILENAME,ORIGINALNAME,UPLOADTIME,FILETYPE,SIZES,ENTID,FILESUFFIX,UPLOADUSERID,CUSTOMERCODE,isupload) values( LIST_ATTACHMENT_ID.Nextval,'{0}','{1}',sysdate,'{2}','{3}','{4}','{5}','404','{6}','1')"; sql = string.Format(sql, "/" + directory + "/" + fs.Name, fs.Name, filetypeid, fs.Size, entid, suffix, enterprisecode); int result = DBMgr.ExecuteNonQuery(sql); if (result > 0 && fs.Name.IndexOf(".txt") > 0) { db.ListRightPush("kd_sheet_topdf_queen", "{ENTID:'" + entid + "',FILENAME:" + "'/" + directory + "/" + fs.Name + "'}");//保存随附文件ID到队列 } content = true; } #endregion catch (Exception ex) { lbl_msg.Text = "database_" + ex.Message; content = false; } return(content); }
private bool update_entorder(FileStruct fs, string directory, string contractno, ftpItem item) { bool content = false; string sql = string.Empty; #region try { string enterprisecode = item.ENTERPRISECODE; string enterprisename = item.ENTERPRISENAME; string prefix = fs.Name.Substring(0, 3); string entid = string.Empty; //判断是否仁宝,仁宝的委托企业字段直接放空 if (item.ENTERPRISECODE == "") { if (prefix == "E1P" || prefix == "E1B" || prefix == "IMP" || prefix == "IMB") { enterprisecode = "3223640003";//海关10位编码 空运出口 enterprisename = "仁宝电子科技(昆山)有限公司"; } if (prefix == "E1W" || prefix == "E2W" || prefix == "E1D" || prefix == "E2D" || prefix == "E7D" || prefix == "IMW" || prefix == "IMD" || prefix == "LMW" || prefix == "LMD" || prefix == "IAD" || prefix == "IEW" || prefix == "IED" || prefix == "E7W" || prefix == "LDD" || prefix == "LGW" || prefix == "LGD" || prefix == "LDW") { enterprisecode = "3223640047"; enterprisename = "仁宝信息技术(昆山)有限公司"; } if (prefix == "E1C" || prefix == "E1Q" || prefix == "E1O" || prefix == "IMQ" || prefix == "IMC" || prefix == "E2Q" || prefix == "E2C" || prefix == "LGC") { enterprisecode = "3223640038"; enterprisename = "仁宝资讯工业(昆山)有限公司"; } if (prefix == "IVS" || prefix == "EAS") { enterprisecode = "3223660037"; enterprisename = "昆山柏泰电子技术服务有限公司"; } } //code是企业编号 仁宝格式 E1Q1603927_sheet.txt int start = fs.Name.LastIndexOf("_"); int end = fs.Name.LastIndexOf("."); string suffix = fs.Name.Substring(end + 1, 3).ToUpper();//文件扩展名 string filetype = fs.Name.Substring(start + 1, end - start - 1).ToUpper(); int filetypeid = 0; switch (filetype) { case "CONTRACT": filetypeid = 50; break; case "INVOICE": filetypeid = 51; break; case "PACKING": filetypeid = 52; break; case "SHEET": filetypeid = 44; break; default: filetypeid = 50; break; } sql = "select * from ent_order where code='" + contractno + "' and ENTERPRISECODE='" + enterprisecode + "'"; DataTable dt_ent = DBMgr.GetDataTable(sql); if (dt_ent.Rows.Count == 0) { sql = "select ENT_ORDER_ID.Nextval from dual"; entid = DBMgr.GetDataTable(sql).Rows[0][0] + ""; sql = @"insert into ent_order(ID,CODE,CREATETIME,SUBMITTIME,UNITCODE,ENTERPRISECODE,ENTERPRISENAME,FILEDECLAREUNITCODE,FILEDECLAREUNITNAME, FILERECEVIEUNITCODE,FILERECEVIEUNITNAME,TEMPLATENAME,CUSTOMDISTRICTCODE,CUSTOMDISTRICTNAME) VALUES ('{3}','{0}',sysdate,sysdate,(select fun_AutoQYBH(sysdate) from dual),'{1}','{2}','{4}','{5}','{6}','{7}','{8}','2369','昆山综保')"; sql = string.Format(sql, contractno, enterprisecode, enterprisename, entid, item.DECLAREUNIUTCODE, item.DECLAREUNITNAME, item.RECIVEUNITCODE, item.RECIVEUNITNAME, item.TEMPLETENAME); DBMgr.ExecuteNonQuery(sql); } else { entid = dt_ent.Rows[0]["ID"] + ""; } //写入随附文件表 sql = @"select * from list_attachment where originalname='" + fs.Name + "' and entid='" + entid + "'"; DataTable dt_att = DBMgr.GetDataTable(sql);//因为客户有可能会重复传文件,此是表记录不需要变化,替换文件即可 if (dt_att.Rows.Count > 0) { sql = "delete from list_attachment where id='" + dt_att.Rows[0]["ID"] + "'"; DBMgr.ExecuteNonQuery(sql); } //dt_att = DBMgr.GetDataTable("select LIST_ATTACHMENT_ID.Nextval ATTACHMENTID from dual"); sql = @"insert into list_attachment(ID,FILENAME,ORIGINALNAME,UPLOADTIME,FILETYPE,SIZES,ENTID,FILESUFFIX,UPLOADUSERID,CUSTOMERCODE,isupload) values( LIST_ATTACHMENT_ID.Nextval,'{0}','{1}',sysdate,'{2}','{3}','{4}','{5}','404','{6}','1')"; sql = string.Format(sql, "/" + directory + "/" + fs.Name, fs.Name, filetypeid, fs.Size, entid, suffix, enterprisecode); int result = DBMgr.ExecuteNonQuery(sql); if (result > 0 && fs.Name.IndexOf(".txt") > 0) { //key应该根据不同公司生成不同的key string keyname = item.REDISKEY; //db.ListRightPush("compal_sheet_topdf_queen", "{ENTID:'" + entid + "',FILENAME:" + "'/" + directory + "/" + fs.Name + "'}");//保存随附文件ID到队列 db.ListRightPush(keyname, "{ENTID:'" + entid + "',FILENAME:" + "'/" + directory + "/" + fs.Name + "'}");//保存随附文件ID到队列 } content = true; } #endregion catch (Exception ex) { content = false; foreach (DataGridViewRow row in this.gr_ftpitem.Rows) { if (row.Cells["ID"].Value.ToString() == item.ID.ToString()) { row.Cells["STATUSFLAG"].Value = ex.Message.ToString(); } } } return(content); }
}//method /// <summary> /// Returns true if file exists /// | if file does not exist, method returns -1 /// | dummy method of FileExists /// </summary> /// <param name="remoteDirectory">directory on ftpServer</param> /// <param name="remoteFileName">filename on ftpServer</param> /// <param name="remFileSize">remote fileSize if file exists else -1</param> /// <returns>True if file exists else false</returns> public bool FileExists(string remoteDirectory, string remoteFileName, out long remFileSize) { var success = false; remFileSize = 0; Uri uri = null; if (remoteDirectory.Contains("ftp://")) { if (!string.IsNullOrEmpty(remoteFileName)) { uri = new Uri(remoteDirectory + "/" + remoteFileName); } else { uri = new Uri(remoteDirectory); } } else { if (!string.IsNullOrEmpty(remoteFileName)) { uri = new Uri("ftp://" + _host + ":" + Port + "/" + remoteDirectory + "/" + remoteFileName); } else { uri = new Uri("ftp://" + _host + ":" + Port + "/" + remoteDirectory); } } var request = (FtpWebRequest)FtpWebRequest.Create(uri) as FtpWebRequest; request.Credentials = new NetworkCredential(UserName, Password); request.Timeout = TimeOut; request.UsePassive = true; request.KeepAlive = KeepAlive; request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; try { using (FtpWebResponse response = request.GetResponse() as FtpWebResponse) { using (StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII)) { string ftpRecord = sr.ReadToEnd(); response.Close(); if (string.IsNullOrEmpty(ftpRecord)) { success = false; } else { string[] ftpRecords = ftpRecord.Split('\n'); var ftpListdirectoryDetails = new FtpListDirectoryDetails(); FileStruct fstruct = ftpListdirectoryDetails.Parse(ftpRecords[0]); remFileSize = fstruct.Size; success = true; } } //using } //using } catch { } return(success); }//method
public static async Task <string> BuilderProtectAsync( string folder, string descript, string userId, string typename, long materialId) { var protect = new ProtectInfomat() { DescriptBytes = descript.PadRight(30, '\0').ToBytes(), UserIdBytes = userId.PadRight(80, '\0').ToBytes(), TypeNameBytes = typename.PadRight(10, '\0').ToBytes(), MaterialIdBytes = longToBytes(materialId) }; var headerBytes = await CompressAsync(StructToBytes(protect)); var headerSizeBytes = BitConverter.GetBytes(headerBytes.Length); var fileInformatSize = Marshal.SizeOf(typeof(FileInformat)); var imageInfo = new FileInfo($"{folder}\\Image.png"); var videoInfo = new FileInfo($"{folder}\\Video.dat"); var imageOffset = 4 + headerBytes.Length + fileInformatSize * 2; var videoOffset = imageOffset + imageInfo.Length; var builderFilename = $"{folder}\\Protect"; using (var stream = File.OpenWrite(builderFilename)) { await stream.WriteAsync(headerSizeBytes, 0, 4); await stream.WriteAsync(headerBytes, 0, headerBytes.Length); var imageInformat = new FileStruct { OffsetBytes = BitConverter.GetBytes((long)imageOffset), LengthBytes = BitConverter.GetBytes((long)imageInfo.Length) }; var imageInformatBytes = StructToBytes(imageInformat); await stream.WriteAsync(imageInformatBytes, 0, imageInformatBytes.Length); var videoInformat = new FileStruct { OffsetBytes = BitConverter.GetBytes((long)videoOffset), LengthBytes = BitConverter.GetBytes((long)videoInfo.Length) }; var videoInformatBytes = StructToBytes(videoInformat); await stream.WriteAsync(videoInformatBytes, 0, videoInformatBytes.Length); using (var imageStream = imageInfo.Open(FileMode.Open)) { await imageStream.CopyToAsync(stream); } using (var videoStream = videoInfo.Open(FileMode.Open)) { await videoStream.CopyToAsync(stream); } } return(builderFilename); }
/// <summary> /// 创建资源 /// </summary> /// <param name="filename"></param> /// <param name="imageFileName"></param> /// <param name="videoFileName"></param> /// <param name="informat"></param> /// <returns></returns> public static async Task MergeAsync(string filename, string imageFileName, string videoFileName, FileInformat informat) { //构建头部 var protect = new ProtectInfomat() { DescriptBytes = informat.DescriptBytes, UserIdBytes = informat.UserIdBytes, TypeNameBytes = informat.TypeNameBytes, // MaterialIdBytes = longToBytes(informat.MaterialIdBytes) }; //压缩头部 var headerBytes = await CompressAsync(StructToBytes(protect)); var headerSizeBytes = BitConverter.GetBytes(headerBytes.Length); //构建图片流信息 var fileInformatSize = Marshal.SizeOf(typeof(FileStruct)); var imageInfo = new FileInfo(imageFileName); var videoInfo = new FileInfo(videoFileName); //更新 位置信息 var imageOffset = 4 + headerBytes.Length + fileInformatSize * 2; var videoOffset = imageOffset + imageInfo.Length; using (var stream = File.OpenWrite(filename)) { //将头部写入流 await stream.WriteAsync(headerSizeBytes, 0, 4); await stream.WriteAsync(headerBytes, 0, headerBytes.Length); //分析图片流位置及大小 var imageInformat = new FileStruct { OffsetBytes = BitConverter.GetBytes((long)imageOffset), LengthBytes = BitConverter.GetBytes(imageInfo.Length) }; //为图片流分配空间 var imageInformatBytes = StructToBytes(imageInformat); await stream.WriteAsync(imageInformatBytes, 0, imageInformatBytes.Length); //分析视频流位置及大小 var videoInformat = new FileStruct { OffsetBytes = BitConverter.GetBytes((long)videoOffset), LengthBytes = BitConverter.GetBytes(videoInfo.Length) }; //为视频流分配空间 var videoInformatBytes = StructToBytes(videoInformat); await stream.WriteAsync(videoInformatBytes, 0, videoInformatBytes.Length); #region 往分配的空间中写入流 using (var imageStream = imageInfo.Open(FileMode.Open)) { await imageStream.CopyToAsync(stream); } using (var videoStream = videoInfo.Open(FileMode.Open)) { await videoStream.CopyToAsync(stream); } #endregion } }
/// <summary> /// 从Unix格式中返回文件信息 /// </summary> /// <param name="Record">文件信息</param> private FileStruct ParseFileStructFromUnixStyleRecord(string Record) { FileStruct f = new FileStruct(); string processstr = Record.Trim(); f.Flags = processstr.Substring(0, 10); f.IsDirectory = (f.Flags[0] == 'd'); processstr = (processstr.Substring(11)).Trim(); _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //跳过一部分 f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); f.Group = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //跳过一部分 string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2]; if (yearOrTime.IndexOf(":") >= 0) //time { processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString()); } f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', 8)); f.Name = processstr; //最后就是名称 return f; }
public static extern bool GetOpenFileName([In, Out] FileStruct ofn);
private void buttonUpdate_Click(object sender, EventArgs e) { try { if (_statusUpdate == true) { EnabledForm(false); if (textBoxName.Text != "") { if (!DataMethod.incorrectChar.IsMatch(textBoxName.Text) && !DataMethod.incorrectChar.IsMatch(richTextBoxComment.Text)) { if (textBoxName.Text.Length <= 50) { if (richTextBoxComment.Text.Length <= 250) { if (MessageBox.Show("Вы действительно желаете изменить информацию о данном файле?", "Изменить файл", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { DataMethod.UpdateFile(_userActive.userId, _fileStruct.fileId, textBoxName.Text.Trim(), richTextBoxComment.Text.Trim()); _statusUpdate = false; _userStruct = DataMethod.GetUser(_userStruct.userId); _fileStruct = DataMethod.GetFile(_fileStruct.fileId); FillForm(); textBoxName.Enabled = false; richTextBoxComment.Enabled = false; buttonUpdate.Text = "Изменить"; } } else { MessageBox.Show("Описание файла должно быть не больше 250 символов.", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Название файла должно быть не больше 50 символов.", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show(@"Название и описание файла не должны содержать следующих символов: \ / : ? \"" < > |.", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Не указано имя файла.", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning); } EnabledForm(true); } else { _statusUpdate = true; textBoxName.Enabled = true; textBoxName.Focus(); richTextBoxComment.Enabled = true; buttonUpdate.Text = "Сохранить"; } } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void ToolStripManagement(object sender, EventArgs e) { //use ProcessFileManagement //delete all copies //trim //show cert //show xciexplorer //show in explorer string message = string.Empty, action = string.Empty, source = string.Empty, destination = string.Empty; FileStruct fileAction = new FileStruct(); ToolStripItem clicked = sender as ToolStripItem; int toolIndex = olvList.ContextMenuStrip.Items.IndexOf(clicked); if (toolIndex < 0) { toolIndex = gameManagementToolStripMenuItem.DropDownItems.IndexOf(clicked); } if (toolIndex == 1) { fileAction.action = FileAction.CompletelyDelete; } if (toolIndex == 2) { fileAction.action = FileAction.Trim; } if (toolIndex == 3) { fileAction.action = FileAction.ShowRenameWindow; } if (toolIndex == 4) { fileAction.action = FileAction.ShowCert; } if (toolIndex == 5) { fileAction.action = FileAction.ShowXciInfo; } if (toolIndex == 6) { fileAction.action = FileAction.ShowInExplorer; } if (toolIndex == 7) { fileAction.action = FileAction.OpenOnTinfoilWeb; } if (Helpers.Settings.config.defaultView == XciLocation.PC) { fileAction.destination = XciLocation.SD; fileAction.source = XciLocation.PC; } else { fileAction.destination = XciLocation.PC; fileAction.source = XciLocation.SD; } switch (fileAction.action) { case FileAction.ShowRenameWindow: formRenamer renamer = new formRenamer(); List <XciItem> renameList = olvList.SelectedObjects.Cast <XciItem>().ToList(); renamer.PopulateList(renameList); renamer.Show(); return; case FileAction.ShowInExplorer: case FileAction.ShowCert: case FileAction.ShowXciInfo: List <XciItem> showInfo = olvList.SelectedObjects.Cast <XciItem>().ToList(); foreach (XciItem item in showInfo) { item.fileAction = Clone(fileAction); ProcessFileManagement(item); } return; case FileAction.OpenOnTinfoilWeb: List <XciItem> openWeb = olvList.SelectedObjects.Cast <XciItem>().ToList(); foreach (XciItem item in openWeb) { if (item.titleId != null || item.titleId.Length > 0) { System.Diagnostics.Process.Start("https://tinfoil.io/Title/" + item.titleId); } } return; default: break; } XciItem xci; int success = 0, failure = 0; action = Enum.GetName(typeof(FileAction), fileAction.action); if (fileAction.action == FileAction.CompletelyDelete) { action = "completely delete (from all locations)"; } if (olvList.SelectedIndices.Count > 1) { if (MessageBox.Show($"Are you sure you want to {action} {olvList.SelectedObjects.Count} games?", $"Confirm {action.ToUpperInvariant()}", MessageBoxButtons.YesNoCancel) != DialogResult.Yes) { return; } List <XciItem> actionList = olvList.SelectedObjects.Cast <XciItem>().ToList(); foreach (XciItem obj in actionList) { xci = Clone(obj); xci.fileAction = Clone(fileAction); if (ProcessFileManagement(xci)) { success++; } else { failure++; } UpdateToolStripLabel($"{action.ToUpperInvariant()} results: Success: {success} Failed: {failure}"); if (fileAction.action == FileAction.Trim) { XciHelper.UpdateXci(xci); } } } else { xci = Clone((XciItem)olvList.GetItem(olvList.SelectedIndex).RowObject); xci.fileAction = fileAction; if (MessageBox.Show($"Are you sure you want to {action} {xci.gameName}?", $"Confirm {action.ToUpperInvariant()}", MessageBoxButtons.YesNoCancel) != DialogResult.Yes) { return; } ProcessFileManagement(xci); if (fileAction.action == FileAction.Trim) { XciHelper.UpdateXci(xci); } } if (fileAction.action == FileAction.CompletelyDelete) { XciHelper.RefreshList(); } }
private void ToolStripFileManagement(object sender, EventArgs e) { XciItem xci; string message = string.Empty, action = string.Empty, source = string.Empty, destination = string.Empty; int success = 0, failure = 0; FileStruct fileAction = new FileStruct(); ToolStripItem clicked = sender as ToolStripItem; ToolStripMenuItem toolStripMenu = fileToolStripMenuItem; int toolIndex = toolStripMenu.DropDownItems.IndexOf(clicked); if (toolIndex < 0) { toolStripMenu = (ToolStripMenuItem)contextMenuStrip.Items[0]; toolIndex = toolStripMenu.DropDownItems.IndexOf(clicked); } Debug.Assert(toolIndex >= 0); if (!IsListIndexUsable()) { return; } if (toolIndex == 0) { fileAction.action = FileAction.Copy; } if (toolIndex == 1) { fileAction.action = FileAction.Move; } if (toolIndex == 2) { fileAction.action = FileAction.Delete; } //Refresh Game Info if (toolIndex == 3) { List <XciItem> filtered = olvList.SelectedObjects.Cast <XciItem>().ToList(); foreach (XciItem obj in filtered) { XciHelper.RefreshXciInBackground(obj); } return; } if (Helpers.Settings.config.defaultView == XciLocation.PC) { fileAction.destination = XciLocation.SD; fileAction.source = XciLocation.PC; } else { fileAction.destination = XciLocation.PC; fileAction.source = XciLocation.SD; } action = Enum.GetName(typeof(FileAction), fileAction.action); source = Enum.GetName(typeof(XciLocation), fileAction.source); destination = Enum.GetName(typeof(XciLocation), fileAction.destination); if (olvList.SelectedIndices.Count > 1) { List <XciItem> filtered = olvList.SelectedObjects.Cast <XciItem>().ToList(); double totalSize = filtered.Sum(x => x.gameSize); double sizeDiff; if (fileAction.action == FileAction.Move || fileAction.action == FileAction.Copy) { try { if ((double)sdInfo.AvailableFreeSpace <= totalSize) { sizeDiff = totalSize - (double)sdInfo.AvailableFreeSpace; MessageBox.Show($"Unable to copy games to SD! {Environment.NewLine} You need {ReadableFileSize(sizeDiff)} more space for this transfer!", "Unable To Transfer", MessageBoxButtons.OK); return; } } catch { } message = $"Are you sure you want to {action} {olvList.SelectedObjects.Count} games ({ReadableFileSize(totalSize)}) to {destination}?"; } if (fileAction.action == FileAction.Delete) { message = $"Are you sure you want to {action} {olvList.SelectedObjects.Count} games from {source}?"; } if (MessageBox.Show(message, $"Confirm {action.ToUpperInvariant()}", MessageBoxButtons.YesNoCancel) != DialogResult.Yes) { return; } foreach (XciItem obj in filtered) { xci = Clone(obj); xci.fileAction = Clone(fileAction); if (ProcessFileManagement(xci)) { success++; } else { failure++; } } if (fileAction.action == FileAction.Copy || fileAction.action == FileAction.Move) { UpdateToolStripLabel($"Games queued for {action.ToUpperInvariant()}: {success}"); } else { UpdateToolStripLabel($"{action.ToUpperInvariant()} results: Success: {success} Failed: {failure}"); } } else { xci = (XciItem)olvList.GetItem(olvList.SelectedIndex).RowObject; if (fileAction.action == FileAction.Move || fileAction.action == FileAction.Copy) { message = $"Are you sure you want to {action} {xci.gameName} to {destination}?"; } if (fileAction.action == FileAction.Delete) { message = $"Are you sure you want to {action} {xci.gameName} from {source}?"; } if (MessageBox.Show(message, $"Confirm {action.ToUpperInvariant()}", MessageBoxButtons.YesNoCancel) != DialogResult.Yes) { return; } xci.fileAction = fileAction; if (ProcessFileManagement(xci)) { UpdateToolStripLabel($"{action.ToUpperInvariant()} successful for {xci.gameName}"); } else { UpdateToolStripLabel($"{action.ToUpperInvariant()} failed for {xci.gameName}"); } } //XciHelper.LoadXcisInBackground(); }
public FileHistory(int fileId) { _fileStruct = DataMethod.GetFile(fileId); this.InitializeComponent(); }
public void AddFile(string newFileName, int blockIndex) { if (newFileName.Substring(0, GamePath.Length) != GamePath) { throw new Exception("Can't add \"" + Path.GetFileName(newFileName) + "\", it must reside inside \n" + GamePath); } var tocBinFilePath = newFileName.Substring(GamePath.Length); if (ExistsFile(newFileName)) { throw new Exception("Can't add \"" + tocBinFilePath + "\",\nit already exist inside PCConsoleTOC.bin."); } /*foreach (chunk chunkElem in chunkList) * { * if (chunkElem.fileList == null) * continue; * foreach (fileStruct fileElem in chunkElem.fileList) * { * if (tocBinFilePath.ToLower() == fileElem.filePath.ToLower()) * { * throw new Exception("Can't add \"" + tocBinFilePath + "\",\nit already exist inside PCConsoleTOC.bin."); * } * } * }*/ var addFileStruct = new FileStruct(); switch (Path.GetExtension(newFileName)) { case ".tlk": case ".tfc": addFileStruct.Flag = 0x09; break; default: addFileStruct.Flag = 0x01; break; } addFileStruct.FilePath = tocBinFilePath; addFileStruct.Exist = true; using (var fileStream = File.OpenRead(newFileName)) { addFileStruct.FileSize = (int)fileStream.Length; using (var sha = SHA1.Create()) { sha.Initialize(); var buffer = new byte[fileStream.Length]; var inputCount = fileStream.Read(buffer, 0, buffer.Length); sha.TransformBlock(buffer, 0, inputCount, null, 0); sha.TransformFinalBlock(buffer, 0, 0); addFileStruct.Sha1 = sha.Hash; } } if (ChunkList[blockIndex].FileList == null) { ChunkList[blockIndex].FileList = new List <FileStruct>(); } ChunkList[blockIndex].FileList.Add(addFileStruct); Changed = true; }
private static extern bool GetSaveFileName([In, Out] FileStruct ofn);
/// <summary> /// 获得文件和目录列表 /// </summary> /// <param name="datastring">FTP返回的列表字符信息</param> private List<FileStruct> GetList(string datastring) { List<FileStruct> myListArray = new List<FileStruct>(); string[] dataRecords = datastring.Split('\n'); //FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords); foreach (string s in dataRecords) { if (s != "") { FileStruct f = new FileStruct(); f = ParseFileStructFromUnixStyleRecord(s); myListArray.Add(f); } } return myListArray; }