public static File createTemp(string prefix, string suffix, File dir) { if (prefix == null || prefix.Length == 0) prefix = "fan"; if (suffix == null) suffix = ".tmp"; string parent = null; if (dir == null) { parent = System.IO.Path.GetTempPath(); } else { if (!(dir is LocalFile)) throw IOErr.make("Dir is not on local file system: " + dir).val; parent = ((LocalFile)dir).m_file.FullName; } try { string name = parent + '\\' + prefix + suffix; int count = 1; while (System.IO.File.Exists(name)) name = parent + '\\' + prefix + (count++) + suffix; LocalFile temp = new LocalFile(new System.IO.FileInfo(name)); temp.create(); return temp; } catch (System.IO.IOException e) { throw IOErr.make(e).val; } }
public async Task WriteAsync_ThrowsArgumentNullException_WhenStreamIsNull() { //Arrange var file = new LocalFile(@"C:\TestPath"); //Act await file.WriteAsync(null); //Exception }
public void Read_ThrowsFileNotFoundException_WhenFileDoesntExist() { //Arrange var file = new LocalFile($@"C:\{Guid.NewGuid()}.txt"); //Act & Assert file.Read(); //Exception }
public Message CreateFileDetailsMessage(Node sendTo, LocalFile file) { var message = new Message(network, MessageType.FileDetails); message.To = sendTo.NodeID; message.Content = new SharedFileListing(file, true); return(message); }
public void Write_ThrowsArgumentNullException_WhenStreamIsNull() { //Arrange var file = new LocalFile(@"C:\TestPath"); //Act file.Write(null); //Exception }
public async Task <IActionResult> OnPost(IFormFile image, IFormFile template, string guid, string title, string keywords, string description) { Template temp = this.context.Set <Template>().Where(t => t.DocumentLink.Equals(guid)).FirstOrDefault(); if (temp == null) { return(Redirect("/templates")); } string toDeleteImage = null, toDeleteDocument = null; if (image != null) { LocalFile localFile = LocalFile.Create(image); await azureFileController.UploadFile(FileType.Images, localFile.LocalPath, localFile.Stream); toDeleteImage = temp.PreviewImageLink; temp.PreviewImageLink = Path.GetFileName(localFile.LocalPath); } if (template != null) { LocalFile localFile = LocalFile.Create(template); await azureFileController.UploadFile(FileType.Templates, localFile.LocalPath, localFile.Stream); toDeleteDocument = temp.DocumentLink; temp.DocumentLink = Path.GetFileName(localFile.LocalPath); } temp.Title = title; temp.Description = description; temp.Keywords = keywords; await context.SaveChangesAsync(); if (!string.IsNullOrEmpty(toDeleteDocument)) { try { await azureFileController.DeleteFile(FileType.Templates, toDeleteDocument); } catch (Exception e) { System.Diagnostics.Trace.TraceError(string.Format("Deleting old Document failed. Guid: {0}. Stack: {1}", toDeleteDocument, e.StackTrace)); } } if (!string.IsNullOrEmpty(toDeleteImage)) { try { await azureFileController.DeleteFile(FileType.Images, toDeleteImage); } catch (Exception e) { System.Diagnostics.Trace.TraceError(string.Format("Deleting old Image failed. Guid: {0}. Stack: {1}", toDeleteImage, e.StackTrace)); } } return(OnGet(temp.ID.ToString())); }
private void ProcessDirectory(LocalDirectory parentDirectory, IO.DirectoryInfo directoryInfo) { if (parentDirectory == null) { throw new ArgumentNullException(nameof(parentDirectory)); } if (directoryInfo == null) { throw new ArgumentNullException(nameof(directoryInfo)); } try { LocalDirectory directory = (LocalDirectory)parentDirectory.GetSubdirectory(directoryInfo.Name); if (directory == null) { directory = parentDirectory.CreateSubDirectory(directoryInfo.Name, directoryInfo.FullName); } foreach (var fileInfo in directoryInfo.EnumerateFiles().Where(f => !f.Name.StartsWith("."))) { IndexingFile?.Invoke(this, new FilenameEventArgs(fileInfo.FullName)); LocalFile file = (LocalFile)directory.GetFile(fileInfo.Name); if (file == null) { file = directory.CreateFile(fileInfo); } else { // XXX: Update file info } if (string.IsNullOrEmpty(file.InfoHash)) { this.hasher.HashFile(file); } } foreach (var subDirectoryInfo in directoryInfo.EnumerateDirectories().Where(d => !d.Name.StartsWith("."))) { //ProcessDirectory(directory, subDirectoryInfo); this.queue.Add(new QueueItem(directory, subDirectoryInfo), this.cancellation.Token); } } catch (ThreadAbortException) { // Canceled, ignore error. } catch (Exception ex) { this.loggingService.LogError("Error while re-indexing shared files:", ex); ErrorIndexing?.Invoke(this, new ErrorEventArgs(ex)); } }
private void PushFile(LocalFile localFile, string ftpParentPath, string ftpPath, FtpClient client) { // https://github.com/hgupta9/FluentFTP/issues/46 using (var readStream = localFile.OpenRead()) using (var writeStream = FtpRetry.ConnectedCall(client, ftpParentPath, c => c.OpenWrite(ftpPath))) { readStream.CopyTo(writeStream, 256 * 1024); } FtpRetry.ConnectedCall(client, ftpParentPath, c => c.SetModifiedTime(ftpPath, localFile.LastWriteTimeUtc)); }
public void Save(LocalFile file) { if (File.Exists(file.Path)) { File.Delete(file.Path); } File.WriteAllBytes(file.Path, file.Data); }
public List <FileResults> Scan(ICompress file, bool testcrc, bool deepScan) { testcrc = testcrc || deepScan; List <FileResults> lstFileResults = new List <FileResults>(); int fileCount = file.LocalFilesCount(); for (int i = 0; i < fileCount; i++) { LocalFile lf = file.GetLocalFile(i); FileResults fileResults = new FileResults(); if (lf.IsDirectory) { fileResults.HeaderFileType = HeaderFileType.Nothing; fileResults.FileStatus = ZipReturn.ZipGood; fileResults.Size = 0; fileResults.CRC = new byte[] { 0, 0, 0, 0 }; fileResults.SHA1 = new byte[] { 0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09 }; fileResults.MD5 = new byte[] { 0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e }; lstFileResults.Add(fileResults); continue; } ZipReturn zr = file.ZipFileOpenReadStream(i, out Stream fStream, out fileResults.Size); if (zr != ZipReturn.ZipGood) { fileResults.FileStatus = zr; } else { int res = CheckSumRead(fStream, fileResults, lf.UncompressedSize, testcrc, deepScan); if (res != 0) { fileResults.FileStatus = ZipReturn.ZipDecodeError; } else { // if we are not testcrc'ing or deepScan'ing then we did not verify the data stream // so we assume it is good. if (!testcrc) { fileResults.CRC = lf.CRC; } fileResults.FileStatus = ByteArrCompare(lf.CRC, fileResults.CRC) ? ZipReturn.ZipGood : ZipReturn.ZipCRCDecodeError; } } lstFileResults.Add(fileResults); } file.ZipFileCloseReadStream(); return(lstFileResults); }
//选定角色后登陆游戏 public void SendMsgC2GSEnterGame(pb.RoleInfo info, bool isNewRole) { Debug.Log("======================>>>SendMsgC2GSEnterGame"); pb.C2GSEnterGame msg = new pb.C2GSEnterGame(); msg.AccountName = LocalFile.Load("AccountName"); msg.SelectedRoleInfo = info; msg.IsNewRole = isNewRole; NetworkManager.Instance.SendToGAS((int)MsgDef.C2GSEnterGame, msg); }
public static File os(string osPath) { System.IO.FileSystemInfo f = (System.IO.Directory.Exists(osPath)) ? new System.IO.DirectoryInfo(osPath) as System.IO.FileSystemInfo : new System.IO.FileInfo(osPath) as System.IO.FileSystemInfo; Uri uri = LocalFile.pathToUri(osPath, f is System.IO.DirectoryInfo); return(new LocalFile(uri, f)); }
public static File make(Uri uri, bool checkSlash) { System.IO.FileSystemInfo f = LocalFile.uriToFile(uri); if (f is System.IO.DirectoryInfo && !checkSlash && !uri.isDir()) { uri = uri.plusSlash(); } return(new LocalFile(uri, f)); }
public void DeleteUploadData(LocalFile file) { string path = GetFilePath(file); if (File.Exists(path)) { File.Delete(path); } }
static async Task DownloadNext() { if (isDownloading || _downloadStack.Count == 0) { return; } isDownloading = true; var url = _downloadStack[0]; try { var files = SL.GetItems <LocalFile>(x => x.Url == url); foreach (var file in files) { try { if (Exists(file.Path)) { DeleteFile(file.Path); } SL.DeleteItem(file); } catch (Exception) { } } var name = Guid.NewGuid().ToString(); var extension = Path.GetExtension(url); var filename = name + extension; var path = CachePath(filename); var pp = PublicPath(filename); await DownloadAsync(url, path); var localFile = new LocalFile { ID = name, Url = url, Path = path }; var result = SL.SaveItem(localFile, true, true) != null; _downloadStack.Remove(url); isDownloading = false; DownloadNext(); if (result) { SendChanged(new Object(), new FileChangedArgs(localFile)); } return; } catch (Exception ex) { SL.Report("Error DownloadFile()", ex); _downloadStack.Remove(url); isDownloading = false; DownloadNext(); return; } }
/// <summary>Creates file on server.</summary> /// <param name="parentMetadata">The parent metadata.</param> /// <param name="fileName">The file name.</param> /// <returns>The <see cref="FileMetadata"/>.</returns> public FileMetadata CreateFileOnServer(FolderMetadata parentMetadata, string fileName) { IFileAsync newFile = parentMetadata.ServerFolder.CreateFileAsync(fileName, null).GetAwaiter().GetResult(); string identifier = this.LocationMapper.GetIdentifierFromServerUri(newFile.Href); string localPath = this.LocationMapper.GetLocalUrlFromIdentifier(identifier); LocalFile localItem = this.LocalStorage.GetFile(localPath); string name = this.GetItemDisplayName(identifier, newFile); return(new FileMetadata(identifier, parentMetadata.Identifier, name, localItem, newFile)); }
/// <summary>Creates file metadata.</summary> /// <param name="itemIdentifier">The item identifier.</param> /// <param name="localItem">The local item.</param> /// <param name="serverItem">The server item.</param> /// <returns>The <see cref="FileMetadata"/>.</returns> private FileMetadata CreateFileMetadata( string itemIdentifier, LocalFile localItem, IFileAsync serverItem = null) { string parentIdentifier = this.LocationMapper.GetParentIdentifier(itemIdentifier); string name = this.GetItemDisplayName(itemIdentifier, serverItem); return(new FileMetadata(itemIdentifier, parentIdentifier, name, localItem, serverItem)); }
private void syncData() { //readGoogleDriveFiles(); //readLocalFiles(); //get metadata string timeStampFileName = getLatestTimeStampFileName(); //Delete Removed Files string LargeDataFolderLocation = txtMyContentFileLocation.Text + "\\LargeData"; using (StreamReader reader = new StreamReader(txtMyContentFileLocation.Text + "\\LFS\\timestamps\\" + timeStampFileName + ".json")) { string data = reader.ReadToEnd(); TimeStamp metaDataFiles = JsonConvert.DeserializeObject <TimeStamp>(data); string[] LocalFilesArray = Directory.GetFiles(LargeDataFolderLocation, "*", SearchOption.AllDirectories); //Console.WriteLine("\nLocal Files:"); //loop through current directory for each file check if exist in metadata, if not, delete OutputArea.Text += "Searching for deleted files\n\n"; foreach (string LocalFile in LocalFilesArray) { bool fileFound = false; string LocalFileRelativePath = LocalFile.Substring(LargeDataFolderLocation.Length); foreach (Data metaDataFile in metaDataFiles.data) { if (metaDataFile.filePath == LocalFileRelativePath) { //Console.WriteLine("Found: " + relativePath); fileFound = true; } } if (!fileFound) { System.IO.File.Delete(LocalFile); OutputArea.Text += "Local File Deleted: " + LocalFile + "\n"; } } } //loop through each directory delete folder if empty cleanUpEmptyFolders(LargeDataFolderLocation); //add all new assets syncNewFiles(LargeDataFolderLocation, timeStampFileName); //Done OutputArea.Text += "\nDone\n"; }
private void PopulateLocalFiles(out List <LocalFile> localFiles) { int emptyFileIndex = 0; int folderIndex = 0; int unpackedStreamsIndex = 0; ulong streamOffset = 0; localFiles = new List <LocalFile>(); if (_header == null) { return; } for (int i = 0; i < _header.FileInfo.Names.Length; i++) { LocalFile lf = new LocalFile { FileName = _header.FileInfo.Names[i] }; if ((_header.FileInfo.EmptyStreamFlags == null) || !_header.FileInfo.EmptyStreamFlags[i]) { lf.StreamIndex = folderIndex; lf.StreamOffset = streamOffset; lf.UncompressedSize = _header.StreamsInfo.Folders[folderIndex].UnpackedStreamInfo[unpackedStreamsIndex].UnpackedSize; lf.CRC = Util.uinttobytes(_header.StreamsInfo.Folders[folderIndex].UnpackedStreamInfo[unpackedStreamsIndex].Crc); streamOffset += lf.UncompressedSize; unpackedStreamsIndex++; if (unpackedStreamsIndex >= _header.StreamsInfo.Folders[folderIndex].UnpackedStreamInfo.Length) { folderIndex++; unpackedStreamsIndex = 0; streamOffset = 0; } } else { lf.UncompressedSize = 0; lf.CRC = new byte[] { 0, 0, 0, 0 }; lf.IsDirectory = (_header.FileInfo.EmptyFileFlags == null) || !_header.FileInfo.EmptyFileFlags[emptyFileIndex++]; if (lf.IsDirectory) { if (lf.FileName.Substring(lf.FileName.Length - 1, 1) != "/") { lf.FileName += "/"; } } } localFiles.Add(lf); } }
private void syncNewFiles(string LargeDataFolderLocation, string timeStampFileName) { using (StreamReader reader = new StreamReader(txtMyContentFileLocation.Text + "\\LFS\\timestamps\\" + timeStampFileName + ".json")) { string data = reader.ReadToEnd(); TimeStamp metaDataFiles = JsonConvert.DeserializeObject <TimeStamp>(data); string[] LocalFilesArray = Directory.GetFiles(LargeDataFolderLocation, "*", SearchOption.AllDirectories); //loop through metadata and check if current directory contain the file. If not, Download OutputArea.Text += "Searching for files to download\n\n"; int filesDownloaded = 0; foreach (Data metaDataFile in metaDataFiles.data) { bool fileFound = false; foreach (string LocalFile in LocalFilesArray) { string LocalFileRelativePath = LocalFile.Substring(LargeDataFolderLocation.Length); if (metaDataFile.filePath == LocalFileRelativePath) { fileFound = true; } } if (!fileFound) { OutputArea.Text += "File Not Found: " + metaDataFile.filePath + "\n"; //download file string saveToLocation = LargeDataFolderLocation + metaDataFile.filePath; FileInfo file = new FileInfo(saveToLocation); file.Directory.Create(); OutputArea.Text += "File will be Save to: " + saveToLocation + "\n"; getFileFromGDrive(metaDataFile.fileName); Google.Apis.Drive.v3.Data.File gFile = getFileFromGDrive(metaDataFile.fileName); downloadFile(service, gFile, saveToLocation); filesDownloaded++; } } if (filesDownloaded == 0) { OutputArea.Text += "No New Files needed to download \n"; } else { OutputArea.Text += "Total Files Downloaded: " + filesDownloaded + "\n"; } } }
/// <summary>Initializes a new instance of the <see cref="FileMetadata"/> class.</summary> /// <param name="identifier">The identifier.</param> /// <param name="parentIdentifier">The parent identifier.</param> /// <param name="name">The name.</param> /// <param name="localItem">The local item.</param> /// <param name="serverItem">The server item.</param> public FileMetadata( string identifier, string parentIdentifier, string name, LocalFile localItem, IFileAsync serverItem = null) : base(identifier, parentIdentifier, name, localItem, serverItem) { this.LocalFile = localItem; this.ServerFile = serverItem; }
public void ZipFileAddDirectory(string filename) { LocalFile lf = new LocalFile { FileName = filename, UncompressedSize = 0, IsDirectory = true, StreamOffset = 0 }; _localFiles.Add(lf); }
internal void SetTrack(LocalFile localFile) { Bass.Init(); Bass.ChannelStop(Stream); Stream = Bass.CreateStream(localFile.Path); AudioProperties.PlaybackLength = Bass.ChannelGetLength(Stream); SetState(State.Playing); }
public List <Event> GetNewEventsFromStorageForUser(string userID) { string eventsText = LocalFile.GetDataFromFile(eventsFile).Result; List <Event> events = JsonConvert.DeserializeObject <List <Event> >(eventsText); DateTime lastCheckDate = GetUserLastCheckDateAndSaveCurrentDate(userID); List <Event> newEvents = (from e in events where DateTime.Parse(e.EventAddDate) > lastCheckDate orderby DateTime.Parse(e.EventAddDate) select e).ToList(); return(newEvents); }
public byte[] GetData() { LocalFile.Refresh(); if (!loadedOnce || LocalFile.LastWriteTime >= lastWrite) { rawData = File.ReadAllBytes(LocalFile.FullName); lastWrite = LocalFile.LastWriteTime; } return(rawData); }
private TreeNode CreateFileNode(LocalFile localFile) { var node = new TreeNode(localFile.DisplayName) { Name = localFile.File.FullName, Tag = localFile }; localFile.FileUpdated += LocalFileOnFileUpdated; m_FileNodes.Add(localFile, node); return(node); }
public async Task WriteAsync_ThrowsArgumentException_WhenStreamIsntReadable() { //Arrange Mock <Stream> streamMock = new Mock <Stream>(); streamMock.Setup(m => m.CanRead).Returns(false); Stream stream = streamMock.Object; var file = new LocalFile(@"C:\TestPath"); //Act & Assert await file.WriteAsync(stream); //Exception }
public void saveTest() { Dictionary <string, int> wordLengthIndex = createWordLengthIndex(); LocalFile file = new LocalFile(LogicalDirectory.Data, "wordLengthIndex.txt"); fileSystemManager.save(wordLengthIndex, file); Dictionary <string, int> loadedWordLengthIndex = (Dictionary <string, int>)fileSystemManager.load(typeof(Dictionary <string, int>), file); Assert.AreEqual(4, loadedWordLengthIndex["test"]); Assert.AreEqual(5, loadedWordLengthIndex["piano"]); Assert.AreEqual(1, loadedWordLengthIndex["I"]); }
public void resetConf() { stage = 1; // 現在的關卡 bossFlag = false; // boss flag playerDead = false; LocalFile lf = new LocalFile(); gameConfig = lf.LoadLocalFile(Application.persistentDataPath, "config.json"); Debug.Log("======================="); Debug.Log("resetConf"); Debug.Log("======================="); }
protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); LocalFiles = new LocalFile(this); FFImageLoading.Forms.Platform.CachedImageRenderer.Init(true); LoadApplication(new App(new AndroidInitializer())); }
private void lstQueue_DragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false); foreach (var filename in files) { if (!filename.EndsWith(".mp3")) { continue; } var file = new LocalFile(new LocalSource("", ""), filename); streamer.Player.EnqueueMusic(file); } }
public static LocalFile getFileInfo(string filePath) { LocalFile currentFile = new LocalFile(); try { int indexOfDot = filePath.LastIndexOf('.'); currentFile.type = filePath.Substring(indexOfDot); } catch (Exception e) { currentFile.type = ""; } try { int indexOfSlash = filePath.LastIndexOf('\\'); currentFile.name = filePath.Substring(indexOfSlash+1); } catch (Exception e) { currentFile.name = filePath; } currentFile.size = new FileInfo(filePath).Length.ToString(); try { int indexOfLastSlash = filePath.LastIndexOf('\\'); currentFile.parentFolder = filePath.Substring(0,indexOfLastSlash); int indexOfSecondSlash = currentFile.parentFolder.LastIndexOf('\\'); currentFile.parentFolder = currentFile.parentFolder.Substring(indexOfSecondSlash+1); } catch (Exception e) { currentFile.name = filePath; } currentFile.location = filePath; if (currentFile.name.ToLower().Contains("thumbs.db") || currentFile.name.ToLower().Contains("albumart") || currentFile.name.ToLower().Contains("desktop.ini") || currentFile.name.ToLower().Contains("folder.jpg")) { //Utils.writeLog("getFileInfo: Ignored file " + filePath); return null; } if ((currentFile.hash = GenerateHash(filePath)) == null) { Utils.writeLog("getFileInfo: Unable to generate hash of file " + filePath); return null; } /* List<string> propertyHeaders = new List<string>(); Dictionary<string, string> properties = new Dictionary<string, string>(); Shell32.Shell shell = new Shell32.Shell(); Shell32.Folder locationFolder; locationFolder = shell.NameSpace(filePath); String s = ""; for (int i = 0; i < short.MaxValue; i++) { string header = locationFolder.GetDetailsOf(null, i); if (String.IsNullOrEmpty(header)) break; propertyHeaders.Add(header); } foreach (Shell32.FolderItem item in locationFolder.Items()) { for (int i = 0; i < propertyHeaders.Count; i++) { properties.Add(propertyHeaders[i], locationFolder.GetDetailsOf(item, i)); s = s + propertyHeaders[i] + " : " + locationFolder.GetDetailsOf(item, i) + "\n"; } } MessageBox.Show(s); */ currentFile.computeKeywords(); return currentFile; }
private void SendLocalFile(string localFile, string requestRange, string connection) { _mLocalFile = new LocalFile(localFile); long startRange; var responseStr = BuildResponse(requestRange, connection, out startRange); _mLocalFile.FileStream.Seek(startRange, SeekOrigin.Begin); try { ClientSocket.BeginSend(Encoding.ASCII.GetBytes(responseStr), 0, responseStr.Length, SocketFlags.None, OnLocalFileSent, ClientSocket); } catch { _mLocalFile.FileStream.Close(); Dispose(); } }
public ZipReturn ZipFileOpenWriteStream(bool raw, bool trrntzip, string filename, ulong uncompressedSize, ushort compressionMethod, out Stream stream) { stream = null; if (ZipOpen != ZipOpenType.OpenWrite) return ZipReturn.ZipWritingToInputFile; LocalFile lf = new LocalFile(_zipFs, filename); ZipReturn retVal = lf.LocalFileOpenWriteStream(raw, trrntzip, uncompressedSize, compressionMethod, out stream); _localFiles.Add(lf); return retVal; }
public ZipReturn ZipFileOpenReadStreamQuick(ulong pos, bool raw, out Stream stream, out ulong streamSize, out ushort compressionMethod) { LocalFile tmpFile = new LocalFile(_zipFs) { LocalFilePos = pos }; _localFiles.Clear(); _localFiles.Add(tmpFile); ZipReturn zr = tmpFile.LocalFileHeaderReadQuick(); if (zr != ZipReturn.ZipGood) { stream = null; streamSize = 0; compressionMethod = 0; return zr; } _readIndex = 0; return tmpFile.LocalFileOpenReadStream(raw, out stream, out streamSize, out compressionMethod); }
public ZipReturn ZipFileOpen(string newFilename, long timestamp, bool readHeaders) { ZipFileClose(); _pZipStatus = ZipStatus.None; _zip64 = false; _centerDirStart = 0; _centerDirSize = 0; _zipFileInfo = null; try { if (!IO.File.Exists(newFilename)) { ZipFileClose(); return ZipReturn.ZipErrorFileNotFound; } _zipFileInfo = new IO.FileInfo(newFilename); if (_zipFileInfo.LastWriteTime != timestamp) { ZipFileClose(); return ZipReturn.ZipErrorTimeStamp; } int errorCode = IO.FileStream.OpenFileRead(newFilename, out _zipFs); if (errorCode != 0) { ZipFileClose(); if (errorCode == 32) return ZipReturn.ZipFileLocked; return ZipReturn.ZipErrorOpeningFile; } } catch (PathTooLongException) { ZipFileClose(); return ZipReturn.ZipFileNameToLong; } catch (IOException) { ZipFileClose(); return ZipReturn.ZipErrorOpeningFile; } ZipOpen = ZipOpenType.OpenRead; if (!readHeaders) return ZipReturn.ZipGood; try { ZipReturn zRet = FindEndOfCentralDirSignature(); if (zRet != ZipReturn.ZipGood) { ZipFileClose(); return zRet; } long endOfCentralDir = _zipFs.Position; zRet = EndOfCentralDirRead(); if (zRet != ZipReturn.ZipGood) { ZipFileClose(); return zRet; } // check if this is a ZIP64 zip and if it is read the Zip64 End Of Central Dir Info if (_centerDirStart == 0xffffffff || _centerDirSize == 0xffffffff || _localFilesCount == 0xffff) { _zip64 = true; _zipFs.Position = endOfCentralDir - 20; zRet = Zip64EndOfCentralDirectoryLocatorRead(); if (zRet != ZipReturn.ZipGood) { ZipFileClose(); return zRet; } _zipFs.Position = (long)_endOfCenterDir64; zRet = Zip64EndOfCentralDirRead(); if (zRet != ZipReturn.ZipGood) { ZipFileClose(); return zRet; } } bool trrntzip = false; // check if the ZIP has a valid TorrentZip file comment if (_fileComment.Length == 22) { if (GetString(_fileComment).Substring(0, 14) == "TORRENTZIPPED-") { CrcCalculatorStream crcCs = new CrcCalculatorStream(_zipFs, true); byte[] buffer = new byte[_centerDirSize]; _zipFs.Position = (long)_centerDirStart; crcCs.Read(buffer, 0, (int)_centerDirSize); crcCs.Flush(); crcCs.Close(); uint r = (uint)crcCs.Crc; crcCs.Dispose(); string tcrc = GetString(_fileComment).Substring(14, 8); string zcrc = r.ToString("X8"); if (String.Compare(tcrc, zcrc, StringComparison.Ordinal) == 0) trrntzip = true; } } // now read the central directory _zipFs.Position = (long)_centerDirStart; _localFiles.Clear(); _localFiles.Capacity = (int)_localFilesCount; for (int i = 0; i < _localFilesCount; i++) { LocalFile lc = new LocalFile(_zipFs); zRet = lc.CenteralDirectoryRead(); if (zRet != ZipReturn.ZipGood) { ZipFileClose(); return zRet; } _zip64 |= lc.Zip64; _localFiles.Add(lc); } for (int i = 0; i < _localFilesCount; i++) { zRet = _localFiles[i].LocalFileHeaderRead(); if (zRet != ZipReturn.ZipGood) { ZipFileClose(); return zRet; } trrntzip &= _localFiles[i].TrrntZip; } // check trrntzip file order if (trrntzip) for (int i = 0; i < _localFilesCount - 1; i++) { if (TrrntZipStringCompare(_localFiles[i].FileName, _localFiles[i + 1].FileName) < 0) continue; trrntzip = false; break; } // check trrntzip directories if (trrntzip) for (int i = 0; i < _localFilesCount - 1; i++) { // see if we found a directory string filename0 = _localFiles[i].FileName; if (filename0.Substring(filename0.Length - 1, 1) != "/") continue; // see if the next file is in that directory string filename1 = _localFiles[i + 1].FileName; if (filename1.Length <= filename0.Length) continue; if (TrrntZipStringCompare(filename0, filename1.Substring(0, filename0.Length)) != 0) continue; // if we found a file in the directory then we do not need the directory entry trrntzip = false; break; } if (trrntzip) _pZipStatus |= ZipStatus.TrrntZip; return ZipReturn.ZipGood; } catch { ZipFileClose(); return ZipReturn.ZipErrorReadingFile; } }
//public List<FTPFile> GetFTPFiles() //{ // try // { // FTPFile[] filesDirectories = ftp.GetFileInfos(); // List<FTPFile> files = new List<FTPFile>(); // foreach (FTPFile f in filesDirectories) // { // if (!f.Dir) // files.Add(f); // } // return files; // } // catch (Exception e) // { // throw e; // } //} public Dictionary<string, FileInfo> GetLocalFiles() { string[] filePaths = Directory.GetFiles(localRootDir); Dictionary<string, FileInfo> fileList = new Dictionary<string, FileInfo>(); foreach (string filePath in filePaths) { LocalFile file = new LocalFile(); FileInfo fileInfo = new FileInfo(filePath); fileList.Add(fileInfo.Name, fileInfo); } return fileList; }
private void DoGetCandidates(IEnumerable<IGetFiles> roots) { var candidates = new List<LocalFile>(); var pool = NSAutoreleasePool.Create(); try { // Get all the files within the directories being edited. var threaded = new List<ThreadedFile>(); var files = new List<string>(); var colors = new List<NSColor>(); foreach (IGetFiles getter in roots) { files.Clear(); colors.Clear(); getter.GetFiles(files, colors); for (int i = 0; i < files.Count; ++i) { string relativePath = files[i].Substring(Path.GetDirectoryName(getter.Path).Length); // use the path up to, and including, the directory being edited threaded.Add(new ThreadedFile(files[i], relativePath, colors[i])); } } // Use a reversed path for the name for any entries with duplicate names. candidates = (from t in threaded select new LocalFile(t)).ToList(); candidates.Sort((lhs, rhs) => lhs.FileName.CompareTo(rhs.FileName)); for (int i = 0; i < candidates.Count - 1; ++i) { string name = candidates[i].FileName; if (candidates[i + 1].FileName == name) { for (int j = i; j < candidates.Count && candidates[j].FileName == name; ++j) { LocalFile f = candidates[j]; candidates[j] = new LocalFile(f, f.RelativePath.ReversePath()); f.DisplayText.release(); } } } } catch (Exception e) { string err = string.Format("Error getting local files: {0}", e.Message); NSApplication.sharedApplication().BeginInvoke(() => DoShowError(err)); } NSApplication.sharedApplication().BeginInvoke(() => DoRefresh(candidates)); pool.release(); }
public LocalFile(LocalFile file, string displayName) : this() { FullPath = file.FullPath; RelativePath = file.RelativePath; FileName = file.FileName; NSDictionary attrs = file.DisplayText.fontAttributesInRange(new NSRange(0, 1)); DisplayText = NSAttributedString.Create(displayName, attrs); DisplayText.retain(); }