private static void CleanFiles(MultipartFileStreamProvider multiPartRequest) { foreach (var f in multiPartRequest.FileData) { File.Delete(f.LocalFileName); } }
private async Task RunAsync(CancellationToken stoppingToken) { var response = await _sqsClient.ReceiveMessageAsync(_servicesSettings.CleanerQueueUrl, stoppingToken); var queueMessage = response.Messages.FirstOrDefault(); if (queueMessage is null) { return; } var(inputFilePath, outputFilePath, thumbnailFilePath) = JsonSerializer.Deserialize <CleanerMessage>(queueMessage.Body) !; if (File.Exists(inputFilePath)) { File.Delete(inputFilePath); } if (File.Exists(outputFilePath)) { File.Delete(outputFilePath); } if (File.Exists(thumbnailFilePath)) { File.Delete(thumbnailFilePath); } await _sqsClient.DeleteMessageAsync(_servicesSettings.CleanerQueueUrl, queueMessage.ReceiptHandle, stoppingToken); }
private void DeleteIfExists(string path) { if (IOFile.Exists(path)) { IOFile.Delete(path); } }
/// <summary> /// Creates a new PluginManager /// </summary> /// <param name="detectCodeChanges"> /// If true will detect changes in the /bin folder and therefor load plugins from the /// cached plugins file if one is found. If false will never use the cache file for plugins /// </param> internal PluginManager(bool detectCodeChanges = true) { _tempFolder = IOHelper.MapPath("~/App_Data/TEMP/PluginCache"); //create the folder if it doesn't exist if (!Directory.Exists(_tempFolder)) { Directory.CreateDirectory(_tempFolder); } //this is a check for legacy changes, before we didn't store the TypeResolutionKind in the file which was a mistake, //so we need to detect if the old file is there without this attribute, if it is then we delete it if (DetectLegacyPluginListFile()) { var filePath = GetPluginListFilePath(); File.Delete(filePath); } if (detectCodeChanges) { //first check if the cached hash is 0, if it is then we ne //do the check if they've changed HaveAssembliesChanged = (CachedAssembliesHash != CurrentAssembliesHash) || CachedAssembliesHash == 0; //if they have changed, we need to write the new file if (HaveAssembliesChanged) { WriteCachePluginsHash(); } } else { //always set to true if we're not detecting (generally only for testing) HaveAssembliesChanged = true; } }
/// <summary> /// 截图 /// </summary> private void CaptureImage(string filePath) { if (File.Exists(filePath)) { File.Delete(filePath); } var rect = Screen.PrimaryScreen.Bounds; var size = new Size(pbImg.Width, pbImg.Height); using (var bitmap = new Bitmap(rect.Width, rect.Height)) { var grp = Graphics.FromImage(bitmap); var location = new Point(Left + 8, Top + 32); grp.CopyFromScreen(location, new Point(0, 0), size); grp.ReleaseHdc(grp.GetHdc()); bitmap.Save(filePath); } using (var srcImg = Image.FromFile(filePath)) using (var bitmap = new Bitmap(pbImg.Width, pbImg.Height)) using (var grp = Graphics.FromImage(bitmap)) { grp.DrawImage(srcImg, 0, 0, new Rectangle(new Point(), size), GraphicsUnit.Pixel); srcImg.Dispose(); using (Image newImg = Image.FromHbitmap(bitmap.GetHbitmap())) newImg.Save(filePath, ImageFormat.Jpeg); } }
public void GetDownloadFormat(Action <string> downloadHandler, string urlPart, params object[] parts) { if (CheckForUserNameAndPassword()) { throw new ArgumentException("If you are not acting as a guest you must supply userName and password"); } if (string.IsNullOrEmpty(urlPart)) { throw new ArgumentException("Url must be specfied"); } if (downloadHandler == null) { throw new ArgumentException("A download handler must be specfied."); } string tempFileName = Path.GetRandomFileName(); var url = CreateUrl(string.Format(urlPart, parts)); try { CreateHttpClient(_configuration.UserName, _configuration.Password, HttpContentTypes.ApplicationJson).GetAsFile(url, tempFileName); downloadHandler.Invoke(tempFileName); } finally { if (File.Exists(tempFileName)) { File.Delete(tempFileName); } } }
private static void DeleteCopiedFiles(List <string> _movedFiles, bool whatIf) { Console.WriteLine("Continue and delete moved files from source dir Y/N"); if (Console.ReadLine() != "y" && Console.ReadLine() != "Y") { return; } Console.WriteLine("Are you sure? Y/N"); if (Console.ReadLine() != "y" && Console.ReadLine() != "Y") { return; } if (whatIf) { foreach (var file in _movedFiles) { Console.WriteLine("Would be deleted: " + file); LogUtility.WriteToLog("Would be deleted: " + file, LogUtility.Level.Info); } return; } foreach (var file in _movedFiles) { File.Delete(file); Print(file + " deleted"); } }
private void chkWindowsStartup_Unchecked(object sender, RoutedEventArgs e) { try { using (WindowsIdentity identity = WindowsIdentity.GetCurrent()) { WindowsPrincipal principal = new WindowsPrincipal(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { // Get the service on the local machine using (TaskService ts = new TaskService()) { var tasks = ts.RootFolder.GetTasks(new Regex(TaskName)); if (tasks.Count != 0) { ts.RootFolder.DeleteTask(TaskName); } } } string lnkPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\" + Application.ResourceAssembly.GetName().Name + ".lnk"; if (File.Exists(lnkPath)) { File.Delete(lnkPath); } } } catch (Exception ex) { MessageBox.Show(ex.Message, LocalizationProvider.Instance.GetTextValue("Messages.Error"), MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// 根据路径获取Excel数据,并转为excel /// </summary> /// <param name="hpf"></param> /// <returns></returns> private DataSet GetDataFromExcel(HttpPostedFileBase hpf) { string uploadFolderPath = Runbow.TWS.Common.Constants.UPLOAD_FOLDER_PATH; string targetPath = Path.Combine(Runbow.TWS.Common.Constants.UPLOAD_FOLDER_PATH, base.UserInfo.ProjectID.ToString(), Runbow.TWS.Common.Constants.TEMPFOLDER); if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } string fileName = base.UserInfo.ID.ToString() + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Path.GetFileName(hpf.FileName); string fullPath = Path.Combine(targetPath, fileName); hpf.SaveAs(fullPath); hpf.InputStream.Close(); Runbow.TWS.Common.ExcelHelper excelHelper = new Runbow.TWS.Common.ExcelHelper(fullPath); DataSet ds = excelHelper.GetAllDataFromAllSheets(); excelHelper.Dispose(); MyFile.Delete(fullPath); return(ds); }
//Saves a BankAccount object to disk file & Text file //******************************************************************************************************************************************* public static void WriteBankAccountToDiskAndText(BankAccount account, string FileName) //******************************************************************************************************************************************* { // Open the file and write the Bank object data that you want to serialize to a disk file // PLUS it saves a copy as a Text file in \\Textfiles folder with same root name + ".txt" try { FileStream fs = new FileStream(FileName, FileMode.Create); BinaryFormatter formatter = new BinaryFormatter( ); formatter.Serialize(fs, account); fs.Close( ); // clean up /* * Now write it out as a named text file in the \\Textfiles folder * */ string s = account.BankAccountNumber + "," + account.CustAccountNumber + "," + account.AccountType + "," + account.Balance + "," + account.DateOpened.ToShortDateString( ) + "," + account.DateClosed.ToShortDateString( ) + "," + account.InterestRate + "," + account.Status + "\r\n"; // This writes the Bank Account object as a std string [record] out in text format in \\textfiles folder string newfname = FileName.Substring(FileName.Length - 21); string path = BankAccount.ReadBankFilePath( ) + "Textfiles\\" + newfname.Substring(0, newfname.Length - 4) + ".txt"; if (File.Exists(path)) { File.Delete(path); // you gotta delete them first, else it appends the data constantly } File.AppendAllText(path, s); } catch { throw new Exception("Failed to handle file in WriteBankAccount Function, line 98 in Serialize.cs"); } }
public string UnpinElement(IPFSElement el, bool deleteFile = true) { try { if (deleteFile) { if (el.IsLinkOnly) { File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\.ipfs\" + el.Name + ".lnk"); File.Delete(eponaSharedFolderPath + "\\" + el.Name + ".lnk"); } else { if (el.FileType.Equals(FileType.FOLDER)) { File.Delete(eponaSharedFolderPath + "\\" + el.Name + ".lnk"); } else { File.Delete(eponaSharedFolderPath + "\\" + el.Name); } } } return(ExecuteCommand("pin rm " + el.Hash)); } catch (Exception) { return(null); } }
public SystemMapping UnmarshallMappings(string databaseFile, PinballXSystem system) { if (!_file.Exists(databaseFile)) { return(new SystemMapping()); } _logger.Info("Reading mappings from {0}...", databaseFile); try { using (var sr = new StreamReader(databaseFile)) using (JsonReader reader = new JsonTextReader(sr)) { try { var systemMapping = _serializer.Deserialize <SystemMapping>(reader); reader.Close(); return(systemMapping); } catch (Exception e) { _logger.Error(e, "Error parsing vpdb.json, deleting and ignoring."); _crashManager.Report(e, "json"); reader.Close(); File.Delete(databaseFile); return(new SystemMapping()); } } } catch (Exception e) { _logger.Error(e, "Error reading vpdb.json, ignoring."); _crashManager.Report(e, "json"); return(new SystemMapping()); } }
public BroadcastResult Handle(VideoConvertedCommand command) { var media = _mediaService.GetById(command.MediaId); media.SetValue(UmbracoAliases.Video.ConvertInProcessPropertyAlias, false); if (!command.Success) { _videoConverterLogService.Log(false, command.Message.ToJson(), command.MediaId); media.SetValue(UmbracoAliases.Video.ThumbnailUrlPropertyAlias, _videoHelper.CreateConvertingFailureThumbnail()); _mediaService.Save(media); return(BroadcastResult.Failure); } using (var fs = new FileStream(command.ConvertedFilePath, FileMode.Open, FileAccess.Read)) { using (var ms = new MemoryStream()) { fs.CopyTo(ms); media.SetValue(UmbracoFilePropertyAlias, Path.GetFileName(command.ConvertedFilePath), ms); } } File.Delete(command.ConvertedFilePath); SaveVideoAdditionProperties(media); _mediaService.Save(media); _videoConverterLogService.Log(true, "Converted succesfully", command.MediaId); return(BroadcastResult.Success); }
public void ItemDClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { FlowPanel.Controls.Remove((PictureBox)sender); Con.TryGetValue((PictureBox)sender, out string file); File.Delete(file); return; } if (e.Clicks > 1) { Con.TryGetValue((PictureBox)sender, out string file); Process prc = new Process(); ProcessStartInfo psi = new ProcessStartInfo(file); if (file.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase)) { psi = new ProcessStartInfo(file.Remove(file.Length - 3, 3)); psi.WorkingDirectory = GetWorkingDirectory(file); psi.Arguments = GetArgument(file); } psi.UseShellExecute = true; psi.RedirectStandardOutput = false; psi.RedirectStandardInput = false; psi.CreateNoWindow = false; prc.StartInfo = psi; prc.Start(); Application.Exit(); } }
public Stream FileArray() { var file = File.ReadAllBytes(FullPathDocumentWord); File.Delete(FullPathDocumentWord); return(new MemoryStream(file)); }
internal static void SendBase(string choice, long id) { try { var zipname = new Regex("[^a-zA-Z0-9]").Replace(choice, "_"); //get rid of non-alphanumeric characters which can cause trouble var path = Path.Combine(Bot.LanguageDirectory, $"BaseZips\\{zipname}.zip"); //where the zipfile will be stored if (File.Exists(path)) { File.Delete(path); } //create our zip file using (var zip = ZipFile.Open(path, ZipArchiveMode.Create)) { var langs = Directory.GetFiles(Bot.LanguageDirectory).Select(x => new LangFile(x)).Where(x => x.Base == choice); //get the base foreach (var lang in langs) { zip.CreateEntryFromFile(Path.Combine(Bot.LanguageDirectory, $"{lang.FileName}.xml"), $"{lang.FileName}.xml", CompressionLevel.Optimal); //add the langs to the zipfile } } //now send the zip file var fs = new FileStream(path, FileMode.Open); Bot.Api.SendDocument(id, new FileToSend($"{zipname}.zip", fs)); } catch (Exception e) { Bot.Api.SendTextMessage(id, e.Message); } }
private static int ConvertPackage(ConvertOptions options) { try { string packageFolderPath = options.Path; var packageDirectory = new DirectoryInfo(packageFolderPath); var existingProjects = packageDirectory.GetFiles("*.csproj"); string packageName = packageDirectory.Name; if (existingProjects.Length > 0) { throw new Exception($"Package {packageName} contains existing .proj file. Remove existing project from package folder and try again."); } Console.WriteLine("Start converting package '{0}'.", packageName); string packagePath = Path.Combine(options.Path, prefix); var backupPath = packageName + ".zip"; if (File.Exists(backupPath)) { File.Delete(backupPath); } ZipFile.CreateFromDirectory(packagePath, backupPath); Console.WriteLine("Created backup package '{0}'.", packageName); var fileNames = options.ConvertSourceCode ? MoveCsFiles(packagePath) : new List <string>(); CorrectingFiles(packagePath); CreateProjectInfo(packagePath, packageName, fileNames); Console.WriteLine("Package '{0}' converted.", packageName); return(0); } catch (Exception e) { Console.WriteLine(e); return(1); } }
public void Dispose() { if (IoFile.Exists(Output)) { IoFile.Delete(Output); } }
private async Task UpdateInstaller() { string downloadUrl = "https://builds.artemis-rgb.com/binaries/Artemis.Installer.exe"; string installerDirectory = Path.Combine(Constants.DataFolder, "installer"); string installerPath = Path.Combine(installerDirectory, "Artemis.Installer.exe"); _logger.Information("UpdateInstaller: Downloading installer from {downloadUrl}", downloadUrl); using HttpClient client = new(); HttpResponseMessage httpResponseMessage = await client.GetAsync(downloadUrl); if (!httpResponseMessage.IsSuccessStatusCode) { throw new ArtemisUIException($"Failed to download installer, status code {httpResponseMessage.StatusCode}"); } _logger.Information("UpdateInstaller: Writing installer file to {installerPath}", installerPath); if (File.Exists(installerPath)) { File.Delete(installerPath); } Core.Utilities.CreateAccessibleDirectory(installerDirectory); await using FileStream fs = new(installerPath, FileMode.Create, FileAccess.Write, FileShare.None); await httpResponseMessage.Content.CopyToAsync(fs); }
private void WaveIn_RecordingStopped(object sender, StoppedEventArgs e) { if (_writer != null) { _writer.Flush(); _writer.Dispose(); _waveIn.Dispose(); } if (CountSeconds >= _userSettings.MinimumRecordedLengthSeconds) { if (!_userSettings.MediaFormat.Equals(MediaFormat.Mp3)) { return; } var mp3TagsInfo = new MediaTags.MP3Tags() { Track = _track, OrderNumberInMediaTagEnabled = _userSettings.OrderNumberInMediaTagEnabled, Count = _userSettings.OrderNumber, CurrentFile = _currentFile }; Task.Run(mp3TagsInfo.SaveMediaTags); return; } _form.WriteIntoConsole(string.Format(FrmEspionSpotify.Rm.GetString($"logDeletingTooShort") ?? $"{0}{1}", BuildFileName(_userSettings.OutputPath, false), _userSettings.MinimumRecordedLengthSeconds)); File.Delete(_currentFile); }
public async Task <IActionResult> Edit(string id, ModVM mod) { var length = (int)mod.File.Length; var buffer = new byte[length]; mod.File.OpenReadStream().Read(buffer, 0, length); var entry = new Mod(); if (!entry.ExtractInfo(buffer)) { return(this.UnprocessableEntity()); } if (id != entry.Name) { return(this.NotFound()); } if (this.ModelState.IsValid) { var existing = this._context.Mod.Find(id); if (existing == null) { return(this.NotFound()); } var user = await this._userManager.GetUserAsync(this.User); if (!existing.Author.Split(", ").Contains(user.AuthorName)) { return(this.Forbid()); } existing.ExtractInfo(buffer, true); entry.UpdateTimeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd hh:mm:ss"); this._logger.LogInformation($"User {user.UserName} ({user.AuthorName}) Update {existing.DisplayName} ({existing.Name})"); try { var filename = existing.FilePath(); if (FileIO.Exists(filename)) { FileIO.Delete(filename); } FileIO.WriteAllBytes(filename, buffer); this._context.Update(existing); await this._context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { throw; } return(this.RedirectToAction(nameof(Details), new { id = entry.Name })); } return(this.View(mod)); }
private static void TranscodeFile() { const string inputFile = @"c:\Users\Ben\Desktop\Bad Chemistry.flac"; const string outputFile = @"c:\Users\Ben\Desktop\Bad Chemistry.m4a"; const string errorsFile = @"c:\Users\Ben\Desktop\Bad Chemistry.log"; using (TagLib.File metadata = TagLib.File.Create(inputFile)) { TimeSpan duration = metadata.Properties.Duration; long inputFileSize = new FileInfo(inputFile).Length; // var converter = new DMCSCRIPTINGLib.Converter(); string encoder = "m4a FDK (AAC)"; // https://wiki.hydrogenaud.io/index.php?title=Fraunhofer_FDK_AAC#Usage_2 string compressionSettings = @"-cli_cmd=""-m 4 -p 2 --ignorelength -S -o {qt}[outfile]{qt} - """; Stopwatch stopwatch = Stopwatch.StartNew(); // converter.Convert(inputFile, outputFile, encoder, compressionSettings, errorsFile); stopwatch.Stop(); double relativeSpeed = duration.TotalMilliseconds / stopwatch.Elapsed.TotalMilliseconds; long outputFileSize = new FileInfo(outputFile).Length; Console.WriteLine( $"Converted {inputFile} to AAC-LC in {stopwatch.Elapsed.TotalSeconds:N} seconds\n{relativeSpeed:N}x speed\n{(double) outputFileSize / inputFileSize:P} file size\n{((double) inputFileSize - outputFileSize) / 1024 / 1024:N} MB saved"); string errorText = File.ReadAllText(errorsFile); if (string.IsNullOrWhiteSpace(errorText)) { errorText = "no errors"; } Console.WriteLine(errorText); File.Delete(errorsFile); } }
protected void DeleteFile(string filename) { if (File.Exists(filename)) { File.Delete(filename); } }
public async Task <IActionResult> RemoveAttachment(RemoveAttachmentViewModel model) { var resume = await _resumeManager.FindByIdAsync(model.Id); if (resume == null) { return(NotFound(model.Id)); } var attachment = resume.Attachments?.FirstOrDefault(f => f.Id == model.AttachmentId); if (attachment == null) { return(NotFound()); } // 删除物理文件 var webRootPath = _environment.WebRootPath; var filePath = $"{webRootPath}/{attachment.FilePath}"; if (IOFile.Exists(filePath)) { IOFile.Delete(filePath); } await _resumeManager.RemoveAttachmentAsync(resume, attachment); Notifier.Success("你已成功删除了一条简历附件记录。"); return(RedirectToAction(nameof(UploadAttachment), new { Id = model.Id })); }
private void CompareWithMr(Table t) { string testFileName = Path.GetFullPath("temp.parquet"); if (F.Exists(testFileName)) { F.Delete(testFileName); } //produce file using (Stream s = F.OpenWrite(testFileName)) { using (var writer = new ParquetWriter(t.Schema, s)) { writer.Write(t); } } //read back Table t2 = ParquetReader.ReadTableFromFile(testFileName); //check we don't have a bug internally before launching MR Assert.Equal(t.ToString("j"), t2.ToString("j"), ignoreLineEndingDifferences: true); string mrJson = ExecAndGetOutput(_javaExecName, $"-jar {_toolsJarPath} cat -j {testFileName}"); Assert.Equal(t.ToString("j"), mrJson); }
private BroadcastResult OnCreateSuccess( VideoConvertedCommand command, IMedia media, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, IMediaService mediaService ) { var name = $"{Path.GetFileNameWithoutExtension(media.Name)}.mp4"; using (var fileStream = new FileStream(command.ConvertedFilePath, FileMode.Open, FileAccess.Read)) using (var memoryStream = new MemoryStream()) { fileStream.CopyTo(memoryStream); media.SetValue(contentTypeBaseServiceProvider, UmbracoAliases.Media.UmbracoFilePropertyAlias, name, memoryStream); } File.Delete(command.ConvertedFilePath); SaveVideoAdditionProperties(media); media.Name = name; mediaService.Save(media); _videoConverterLogService.Log(true, "Converted successfully", command.MediaId); return(BroadcastResult.Success); }
public static void SaveAuthToken() { if (sessionData == null || sessionData.refresh_token == null) { return; } try { if (FileUtils.Exists(tokenPath)) { FileUtils.Delete(tokenPath); } FileStream fs = FileUtils.Create(tokenPath); StreamWriter writer = new StreamWriter(fs, Encoding.UTF8); writer.WriteLine(sessionData.refresh_token); writer.Flush(); writer.Close(); writer.Dispose(); fs.Close(); fs.Dispose(); } catch (Exception e) { //file not yet created MessageBox.Show(e.GetType().ToString() + ": " + e.Message + "\n\n" + e.StackTrace); } }
public void Delete(bool cacheOnly = false) { foreach (var item in File.cache.Copy()) { if (item.Value.Contains(this)) { File.cache[item.Key] = item.Value.Remove(this); if (File.cache[item.Key].Length < 1) { File.cache.Remove(item.Key); } } } if (!this.isFolder) { if (!cacheOnly) { SystemFile.Delete(this.path); } File.filesByType[this.extension].Remove(this); File.filesByPath[this.directory].Remove(this); return; } if (!cacheOnly) { Directory.Delete(this.path); } File.folders.Remove(this.path); }
private void DeleteFileIfExists(string path) { if (File.Exists(path)) { File.Delete(path); } }
public static void SendAllFiles(long id) { //need to zip up all the files var path = Path.Combine(Bot.RootDirectory, "languages.zip"); if (File.Exists(path)) { File.Delete(path); } //create our zip file using (var zip = ZipFile.Open(path, ZipArchiveMode.Create)) { var langs = Directory.GetFiles(Bot.LanguageDirectory); foreach (var lang in langs) { zip.CreateEntryFromFile(lang, lang, CompressionLevel.Optimal); //add the langs to the zipfile } } //now send the file var fs = new FileStream(path, FileMode.Open); Bot.Api.SendDocument(id, new FileToSend("languages.zip", fs)); }
public void Init(Ioctls ioctls, Core core, Runtime runtime) { IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication(); MoSync.SystemPropertyManager.RegisterSystemPropertyProvider("mosync.path.local", delegate(String key) { // The isolated storage becomes the "root" return "/"; } ); ioctls.maFileOpen = delegate(int _path, int _mode) { String path = core.GetDataMemory().ReadStringAtAddress(_path); path = ConvertPath(path); File file = null; FileAccess access = 0; if (_mode == MoSync.Constants.MA_ACCESS_READ) { access = FileAccess.Read; } else if (_mode == MoSync.Constants.MA_ACCESS_READ_WRITE) { access = FileAccess.ReadWrite; } else { throw new Exception("Invalid file access mode"); } file = new File(path, access); if (file.IsDirectory) { if (isolatedStorage.FileExists(path)) return MoSync.Constants.MA_FERR_WRONG_TYPE; } else { if (isolatedStorage.DirectoryExists(path)) return MoSync.Constants.MA_FERR_WRONG_TYPE; try { file.TryOpen(); } catch (IsolatedStorageException e) { MoSync.Util.Log(e); return MoSync.Constants.MA_FERR_GENERIC; } } mFileHandles.Add(mNextFileHandle, file); return mNextFileHandle++; }; ioctls.maFileClose = delegate(int _file) { File file = mFileHandles[_file]; file.Close(); mFileHandles.Remove(_file); return 0; }; ioctls.maFileRead = delegate(int _file, int _dst, int _len) { File file = mFileHandles[_file]; if (file.IsDirectory) return MoSync.Constants.MA_FERR_WRONG_TYPE; IsolatedStorageFileStream fileStream = file.FileStream; if (fileStream == null) return MoSync.Constants.MA_FERR_GENERIC; core.GetDataMemory().WriteFromStream(_dst, fileStream, _len); return 0; }; ioctls.maFileReadToData = delegate(int _file, int _data, int _offset, int _len) { File file = mFileHandles[_file]; if (file.IsDirectory) return MoSync.Constants.MA_FERR_WRONG_TYPE; IsolatedStorageFileStream fileStream = file.FileStream; if (fileStream == null) return MoSync.Constants.MA_FERR_GENERIC; Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); //Memory data = (Memory)dataRes.GetInternalObject(); Stream data = (Stream)dataRes.GetInternalObject(); MoSync.Util.CopySeekableStreams(fileStream, (int)fileStream.Position, data, _offset, _len); //data.WriteFromStream(_offset, fileStream, _len); return 0; }; ioctls.maFileWriteFromData = delegate(int _file, int _data, int _offset, int _len) { File file = mFileHandles[_file]; if (file.IsDirectory) return MoSync.Constants.MA_FERR_WRONG_TYPE; IsolatedStorageFileStream fileStream = file.FileStream; if (fileStream == null) return MoSync.Constants.MA_FERR_GENERIC; Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); //Memory data = (Memory)dataRes.GetInternalObject(); Stream data = (Stream)dataRes.GetInternalObject(); //byte[] bytes = new byte[_len]; //data.ReadBytes(bytes, _offset, _len); MoSync.Util.CopySeekableStreams( data, _offset, fileStream, (int)fileStream.Position, _len); //fileStream.Write(bytes, 0, _len); fileStream.Flush(); return 0; }; ioctls.maFileWrite = delegate(int _file, int _src, int _len) { File file = mFileHandles[_file]; if (file.IsDirectory) return MoSync.Constants.MA_FERR_WRONG_TYPE; IsolatedStorageFileStream fileStream = file.FileStream; if (fileStream == null) return MoSync.Constants.MA_FERR_GENERIC; byte[] bytes = new byte[_len]; core.GetDataMemory().ReadBytes(bytes, _src, _len); fileStream.Write(bytes, 0, _len); fileStream.Flush(); return 0; }; ioctls.maFileSeek = delegate(int _file, int _offset, int _whence) { File file = mFileHandles[_file]; if (file.IsDirectory) return MoSync.Constants.MA_FERR_WRONG_TYPE; IsolatedStorageFileStream fileStream = file.FileStream; SeekOrigin origin; switch (_whence) { case MoSync.Constants.MA_SEEK_SET: origin = SeekOrigin.Begin; break; case MoSync.Constants.MA_SEEK_CUR: origin = SeekOrigin.Current; break; case MoSync.Constants.MA_SEEK_END: origin = SeekOrigin.End; break; default: throw new Exception("maFileSeek whence"); } try { return (int)fileStream.Seek(_offset, origin); } catch (IOException e) { MoSync.Util.Log(e); return MoSync.Constants.MA_FERR_GENERIC; } }; ioctls.maFileTell = delegate(int _file) { File file = mFileHandles[_file]; if (file.IsDirectory) return MoSync.Constants.MA_FERR_WRONG_TYPE; IsolatedStorageFileStream fileStream = file.FileStream; return (int)fileStream.Position; }; ioctls.maFileExists = delegate(int _file) { File file = mFileHandles[_file]; return file.Exists ? 1 : 0; }; ioctls.maFileCreate = delegate(int _file) { File file = mFileHandles[_file]; if (file.Exists) return MoSync.Constants.MA_FERR_GENERIC; file.Create(); return 0; }; ioctls.maFileDelete = delegate(int _file) { File file = mFileHandles[_file]; try { file.Delete(); } catch (IsolatedStorageException e) { MoSync.Util.Log(e); return MoSync.Constants.MA_FERR_GENERIC; } return 0; }; ioctls.maFileSize = delegate(int _file) { File file = mFileHandles[_file]; return file.Size(); }; ioctls.maFileAvailableSpace = delegate(int _file) { File file = mFileHandles[_file]; return file.AvailableSpace(); }; ioctls.maFileTotalSpace = delegate(int _file) { File file = mFileHandles[_file]; return file.TotalSpace(); }; ioctls.maFileDate = delegate(int _file) { File file = mFileHandles[_file]; return Util.ToUnixTimeUtc(file.Date().ToFileTime()); }; ioctls.maFileRename = delegate(int _file, int _newName) { File file = mFileHandles[_file]; String newName = core.GetDataMemory().ReadStringAtAddress(_newName); newName = ConvertPath(newName); if (newName.Contains("\\")) { if (newName[0] != '\\') throw new Exception("Invalid newName"); } else { // add directory of old file. newName = Path.GetDirectoryName(file.Path) + "\\" + newName; } file.Rename(newName); return 0; }; ioctls.maFileTruncate = delegate(int _file, int _offset) { File file = mFileHandles[_file]; file.Truncate(_offset); return 0; }; ioctls.maFileListStart = delegate(int _path, int _filter, int _sorting) { // todo: respect _sorting. String path = core.GetDataMemory().ReadStringAtAddress(_path); path = ConvertPath(path); String filter = core.GetDataMemory().ReadStringAtAddress(_filter); String pattern = path + filter; IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); FileList fl = new FileList(); fl.dirs = isf.GetDirectoryNames(pattern); fl.files = isf.GetFileNames(pattern); fl.pos = 0; mFileListHandles.Add(mNextFileListHandle, fl); return mNextFileListHandle++; }; ioctls.maFileListNext = delegate(int _list, int _nameBuf, int _bufSize) { FileList fl = mFileListHandles[_list]; String name; if (fl.pos < fl.dirs.Length) name = fl.dirs[fl.pos] + "/"; else if (fl.pos < fl.dirs.Length + fl.files.Length) name = fl.files[fl.pos - fl.dirs.Length]; else return 0; if (name.Length >= _bufSize) return name.Length; core.GetDataMemory().WriteStringAtAddress(_nameBuf, name, _bufSize); fl.pos++; return name.Length; }; ioctls.maFileListClose = delegate(int _list) { FileList fl = mFileListHandles[_list]; mFileListHandles.Remove(_list); return 0; }; }
public void Init(Syscalls syscalls, Core core, Runtime runtime) { runtime.RegisterCleaner(delegate() { CleanDictionary(mFileHandles); CleanDictionary(mStoreHandles); mFileListHandles.Clear(); }); // todo: store "stores" in a separate location from the filesystem, // to avoid clashes. syscalls.maOpenStore = delegate(int _name, int _flags) { String name = core.GetDataMemory().ReadStringAtAddress(_name); name = ConvertPath(name); File file = new File(name, FileAccess.ReadWrite); if (file.IsDirectory) { throw new Exception("Invalid store name"); } if (file.Exists) file.TryOpen(); else if ((_flags & MoSync.Constants.MAS_CREATE_IF_NECESSARY) != 0) { file.Create(); } else return MoSync.Constants.STERR_NONEXISTENT; if (file.FileStream == null) return MoSync.Constants.STERR_GENERIC; mStoreHandles.Add(mNextStoreHandle, file); return mNextStoreHandle++; }; syscalls.maWriteStore = delegate(int _store, int _data) { File file = mStoreHandles[_store]; IsolatedStorageFileStream fileStream = file.FileStream; fileStream.SetLength(0); Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); Stream data = (Stream)dataRes.GetInternalObject(); data.Seek(0, SeekOrigin.Begin); //fileStream.Write(data.GetData(), 0, data.GetData().Length); data.CopyTo(fileStream); return 1; }; syscalls.maReadStore = delegate(int _store, int _placeholder) { File file = mStoreHandles[_store]; IsolatedStorageFileStream fileStream = file.FileStream; //Memory mem = new Memory((int)fileStream.Length); MemoryStream mem = new MemoryStream((int)fileStream.Length); fileStream.Seek(0, SeekOrigin.Begin); fileStream.Read(mem.GetBuffer(), 0, (int)fileStream.Length); runtime.SetResource(_placeholder, new Resource(mem, MoSync.Constants.RT_BINARY)); return MoSync.Constants.RES_OK; }; syscalls.maCloseStore = delegate(int _store, int _delete) { File file = mStoreHandles[_store]; file.Close(); if (_delete != 0) file.Delete(); mStoreHandles.Remove(_store); }; }