public async Task CreateFileInternalAsync( string fullFilePath, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default) { await using FileStream stream = IOFile.Create(fullFilePath); await stream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false); }
public void CalcForFolder() { InitializeData(); const int itemCount = 10; if (!Directory.Exists(Folder)) { Directory.CreateDirectory(Folder); } ImportAndValidate("Construction.xlsx", stream => { for (var i = 0; i < itemCount; i++) { using (var fileStream = File.Create(Path.Combine(Folder, $"{i}.xlsx"))) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } } }); foreach (var file in Directory.GetFiles(Folder, "*.xlsx")) { Console.WriteLine($"Processing {Path.GetFileName(file)}"); CalculatorHelper.CalcAndExportExcel(file); } var count = 0; foreach (var file in Directory.GetFiles(Folder, "*process")) { count++; } Console.WriteLine(count); }
public async Task <JsonResult> UploadHomeReport(string i) { try { foreach (string file in Request.Files) { var fileContent = Request.Files[file]; if (fileContent != null && fileContent.ContentLength > 0) { // get a stream var stream = fileContent.InputStream; // and optionally write the file to disk var fileName = Path.GetFileName(file); var path = Path.Combine(Server.MapPath("~/upload"), fileName); using (var fileStream = SO.Create(path)) { stream.CopyTo(fileStream); } } } } catch (Exception) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json("Upload failed")); } return(Json("File uploaded successfully")); }
public TemporaryLocalFile(File backingFile) { _backingFile = backingFile; if (!backingFile.Exists()) backingFile.Create(); }
public void ReadsEventsFromBufferFiles() { using var tmp = new TempFolder(); var fn = tmp.AllocateFilename("clef"); var lines = IOFile.ReadAllText(Path.Combine("Resources", "ThreeBufferedEvents.clef.txt"), Encoding.UTF8).Split(new [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); using (var f = IOFile.Create(fn)) using (var fw = new StreamWriter(f, Encoding.UTF8)) { foreach (var line in lines) { fw.WriteLine(line); } } var position = new FileSetPosition(0, fn); var count = 0; PayloadReader.ReadPayload(1000, null, ref position, ref count, out var mimeType); Assert.Equal(SeqIngestionApi.CompactLogEventFormatMediaType, mimeType); Assert.Equal(3, count); Assert.Equal(465 + 3 * (Environment.NewLine.Length - 1), position.NextLineStart); Assert.Equal(fn, position.File); }
public void ShouldCreateJunctionPoint() { var path = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), Path.GetRandomFileName()); Directory.CreateDirectory(path); var file = Path.Combine(path, "file.txt"); using (File.Create(file)) { } var junctionPath = string.Format("{0}+junction", path); JunctionPoint.Create(junctionPath, path, true); var junctionFiles = Directory.GetFiles(junctionPath); Assert.That(junctionFiles.Length, Is.EqualTo(1)); Assert.That(junctionFiles[0], Is.EqualTo(Path.Combine(junctionPath, "file.txt"))); JunctionPoint.Delete(junctionPath); Assert.That(Directory.Exists(junctionPath), Is.False); Assert.That(File.Exists(file), Is.True); }
public static void TestJson() { try { var filePath = @"C:\Users\Arash\documents\visual studio 2015\Projects\Instagram\BTCPostBot\JsonMessages\EslPodMessages.json"; if (!File.Exists(filePath)) { File.Create(filePath); } var jsonData = File.ReadAllText(filePath); JArray jsonArray = JArray.Parse(jsonData); var setting = new JsonSerializerSettings(); setting.NullValueHandling = NullValueHandling.Ignore; var msgList = JsonConvert.DeserializeObject <List <Message> >(jsonData, setting) ?? new List <Message>(); jsonData = JsonConvert.SerializeObject(msgList); File.WriteAllText(filePath, jsonData); } catch (Exception ex) { Console.WriteLine($"error in appending message to json file. {ex.Message}"); throw; } }
public void saveFile(object sender, EventArgs args) { FileChooserDialog filesaveDialog = new FileChooserDialog("Save File", this, FileChooserAction.Save); filesaveDialog.AddButton(Gtk.Stock.Cancel, Gtk.ResponseType.Cancel); filesaveDialog.AddButton(Gtk.Stock.Save, Gtk.ResponseType.Ok); if (!File.Exists(activeFile)) { var respone = filesaveDialog.Run(); if (respone == (int)Gtk.ResponseType.Ok) { activeFile = filesaveDialog.Filename; string currentText = sourceView.Buffer.Text; var lm = LanguageManager.Default; var lang = lm.GuessLanguage(activeFile, ""); sourceView.Buffer.Language = lang; if (lang != null) { languageSelectorButton.Label = lang.Name; } else { languageSelectorButton.Label = "Text"; } statusBarLabel.Text = "Saved File"; previousText = currentText; headerBar.Subtitle = activeFile; headerBar.Title = headerBarOringalText; isChangeSaved = true; // StreamWriter writer = new StreamWriter(activeFile, false); // writer.Write(currentText); using (var stream = File.Create(activeFile)) { using (TextWriter tw = new StreamWriter(stream)) { tw.Write(currentText); } } File.WriteAllText(activeFile, currentText); // Console.WriteLine("ok"); } // else if (respone == (int) Gtk.ResponseType.Cancel) // { // Console.WriteLine("cancel"); // } filesaveDialog.Dispose(); } else { headerBar.Subtitle = activeFile; headerBar.Title = headerBarOringalText; isChangeSaved = true; string currentText = sourceView.Buffer.Text; previousText = currentText; File.WriteAllText(activeFile, currentText); } }
public static async Task <FileInfo> ToFile(this Stream stream, string path) { using var file = IOFile.Create(path); await stream.CopyToAsync(file).ConfigureAwait(false); return(new FileInfo(path)); }
//UserManagement private void MainWindow_OnInitialized(object?sender, EventArgs e) { //create history if (!File.Exists(path_last)) { //Create Directory and File for the Config Directory.CreateDirectory(path_last.Remove(path_last.LastIndexOf("\\"))); var tmp = File.Create(path_last); tmp.Close(); } var filePath = @".\Config\config.txt"; //Get Last Config from Login Data if (File.Exists(@".\Config\config.txt")) { using (FileStream fs = File.OpenRead(filePath)) { using (StreamReader reader = new StreamReader(fs)) { ClientId = reader.ReadLine(); ClientSecret = reader.ReadLine(); BimId = reader.ReadLine(); AdminMail = reader.ReadLine(); } } } }
private async Task HandleLinkAsync(Message receivedMessage, Message sentMessage, string linkOrFileName, string inputFilePath, CancellationToken cancellationToken) { using var request = new HttpRequestMessage(HttpMethod.Get, linkOrFileName); using var response = await _client.SendAsync(request, cancellationToken); var message = response.StatusCode switch { HttpStatusCode.Unauthorized => $"{linkOrFileName}\nI am not authorized to download video from this source 🚫", HttpStatusCode.Forbidden => $"{linkOrFileName}\nMy access to this video is forbidden 🚫", HttpStatusCode.NotFound => $"{linkOrFileName}\nVideo not found ⚠️", HttpStatusCode.InternalServerError => $"{linkOrFileName}\nServer error 🛑", _ => null }; if (message != null) { await _bot.EditMessageTextAsync(new(sentMessage.Chat.Id), sentMessage.MessageId, message, cancellationToken : cancellationToken); return; } await using var fileStream = File.Create(inputFilePath); await response.Content.CopyToAsync(fileStream, cancellationToken); await SendMessageAsync(receivedMessage, sentMessage, inputFilePath, cancellationToken); }
public async Task <IActionResult> PostWithFile() { FormValueProvider formModel; var postedFilePath = Path.GetTempFileName(); using (var stream = IOFile.Create(postedFilePath)) { formModel = await Request.StreamFile(stream); } var model = new SessionModel(); var bindingSuccessful = await TryUpdateModelAsync(model, prefix : "", valueProvider : formModel); if (!bindingSuccessful) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } } try { var message = SavePostedFile(postedFilePath, model); return(await SaveMessageAndReturnResponse(message)); } catch (Microsoft.AspNetCore.Http.BadHttpRequestException) { return(BadRequest()); } }
private void WriteLyricsFile() { if (_trackInfo.Lyrics.SyncedLyrics == null) { return; } IEnumerable <SyncedLyrics> syncedLyrics = _trackInfo.Lyrics.SyncedLyrics .Where(y => y != null) .Where(x => !string.IsNullOrWhiteSpace(x.Timestamp) || !string.IsNullOrWhiteSpace(x.Line)); string lyricsFormatted = string.Join("\r\n", syncedLyrics.Select(x => x.Timestamp + x.Line)); string lyricFilePath = Path.Combine( Path.GetDirectoryName(_filepath), Path.GetFileNameWithoutExtension(_filepath) + ".lrc"); try { using (FileStream fileStream = File.Create(lyricFilePath)) { using (var sw = new StreamWriter(fileStream)) { sw.Write(lyricsFormatted); } } } catch (IOException ex) { Console.WriteLine(ex.Message); } }
public static void save() { 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 HttpResponseMessage Export([FromBody] AppVsdx appVsdx) { var sessionId = Guid.NewGuid().ToString(); var fileNameWithOutExtension = Path.GetFileNameWithoutExtension(appVsdx.filename); var filePath = CreateTempFile(fileNameWithOutExtension + ".vsdx", sessionId); string outputType = ""; var fileDirectory = Path.GetDirectoryName(filePath); var outPath = ""; using (FileStream stream = File.Create(filePath)) { _service.fileName = appVsdx.filename.Split('.')[0]; _service.addPagesXML(appVsdx.pagesName, appVsdx.images, appVsdx.pageLayers, appVsdx.modelsAttr, appVsdx.pagesXml); _service.createVsdxSkeleton(appVsdx.pagesName); _service.Zip(_service.fileName, stream); outputType = Path.GetExtension(appVsdx.filename).Replace(".", ""); outPath = ConvertDoc(appVsdx.filename, fileNameWithOutExtension, filePath, fileDirectory, outputType); HttpResponseMessage response = new HttpResponseMessage(); response.Content = new StreamContent(File.OpenRead(outPath)); response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = System.Web.HttpUtility.UrlEncode(Path.GetFileName(outPath), System.Text.Encoding.UTF8); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return(response); } }
public void Copy_ShouldCopyFolder_WithItsContent() { var imageFileBuilderMock = new Mock <IImageFileBuilder>(); var sourcePath = TestFolder + "FB51D97B-5106-45EC-8EA6-A8ACE3EA7558\\"; var destinationDirectoryPath = TestFolder + "E5C698D6-C470-412C-8F3E-703100AD2A79\\"; var subFolder1 = "folder1\\"; var subFolder2 = "folder2\\"; var file1 = "testFile1.jpg"; Directory.CreateDirectory(sourcePath); Directory.CreateDirectory(destinationDirectoryPath); Directory.CreateDirectory(sourcePath + subFolder1); Directory.CreateDirectory(sourcePath + subFolder2); var fileStream = File.Create(sourcePath + subFolder2 + file1); fileStream.Close(); var service = new DirectoryService(imageFileBuilderMock.Object); service.Copy(sourcePath, destinationDirectoryPath); Assert.True(Directory.Exists(sourcePath + subFolder1) && Directory.Exists(destinationDirectoryPath + subFolder1) && File.Exists(sourcePath + subFolder2 + file1) && File.Exists(sourcePath + subFolder2 + file1)); }
private static void EnsureTemplateFile(string path) { path = IOHelper.MapPath(path); Directory.CreateDirectory(Path.GetDirectoryName(path)); File.Create(path).Close(); }
public void NewLog(string dateString, string message, string prefix = "LogFile_", string extension = "txt") { try { string fileName = String.Format("{0}{1}{2}{3}{4}", prefix, "_", dateString, ".", extension); string fileDirectory = directoryPath + fileName; if (!ManageFile.Exists(fileDirectory)) { var textfile = ManageFile.Create(fileDirectory); textfile.Close(); } using (TextWriter file = new StreamWriter(fileDirectory)) { file.WriteLine(message); file.Close(); } success = true; } catch { success = false; } }
public void ShouldGetFileInfoWithMultipleHardLinks() { var path = IOPath.GetTempPath(); path = IOPath.Combine(path, IOPath.GetRandomFileName()); var file = IOFile.Create(path); file.Close(); var linkPath = IOPath.GetTempPath(); linkPath = IOPath.Combine(linkPath, IOPath.GetRandomFileName()); CFile.CreateHardLink(linkPath, path); try { var fileInfo = new CFileInfo(path); Assert.That(fileInfo.LinkCount, Is.EqualTo(2), "LinkCount"); } finally { IOFile.Delete(path); IOFile.Delete(linkPath); } }
public IPFSManager(string exePath) { bool canRead = !File.Exists(lockFile); while (!canRead) { Thread.Sleep(100); canRead = !File.Exists(lockFile); if (!canRead) { using (File.Create(waitFile)) { } HasWaited = true; } } File.Delete(waitFile); CreateLock(); pathExecutable = exePath; if (File.Exists(jsonFilePath)) { string json = File.ReadAllText(jsonFilePath); elements = new ArrayList(JsonConvert.DeserializeObject <List <IPFSElement> >(json)); } }
public void CanDownloadLargerFile() { var project = TestHelpers.CreateRandomTestProject(Client); var appResult = TestHelpers.CreateRandomTestAppResult(Client, project); var file = File.Create(string.Format("UnitTestFile_{0}", appResult.Id)); var data = new byte[(1024 * 1024) * 5]; new Random().NextBytes(data); file.Write(data, 0, data.Length); file.Close(); var response = Client.UploadFileToAppResult(new UploadFileToAppResultRequest(appResult.Id, file.Name), null); Assert.NotNull(response); Assert.True(response.Response.UploadStatus == FileUploadStatus.complete); string fileName = "DownloadedFile-" + StringHelpers.RandomAlphanumericString(5); using (var fs = new FileStream(fileName, FileMode.OpenOrCreate)) { Client.DownloadFile(response.Response.Id, fs); Assert.Equal(fs.Length, data.Length); byte[] actual = new byte[data.Length]; fs.Position = 0; fs.Read(actual, 0, data.Length); Assert.True(Enumerable.SequenceEqual(data, actual)); } }
private void SendFile(string username, string app, string path = "") { foreach (var file in Request.Form.Files) { var slash = Core.Extensions.String.GetOsSlash(); var p = path.IsEmpty() ? $"{Directory.GetCurrentDirectory()}{slash}{bucket}{slash}{username}{slash}{app}" : $"{Directory.GetCurrentDirectory()}{slash}{bucket}{slash}{username}{slash}{app}{slash}{path}"; if (!Directory.Exists(p)) { Directory.CreateDirectory(p); } var fileKey = $"{p}/{file.FileName}"; if (!FileManager.Exists(fileKey)) { using (var stream = FileManager.Create(fileKey)) { file.CopyTo(stream); } } } ClearCachedItems(); }
// mantiene aperto il file finche non termina lo scopo // Azione sincrona: dobbiamo apsettare la fine di lettura e scrittura prima di poter fare altre operazioni di interfaccia //processo asincrono: non dobbiamo apsettare la fine di lettura e scrittura prima di poter fare altre operazioni di interfaccia public async static Task LetturaScritturaFileAsync() // se è asincrono bisogna sempre mettere la keyWork TASK che il ritorno { try { string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Testo.txt"); // faccio path //per utilizzare filestrem devo usare la keyword using e dentro indico la validità using (FileStream file = File.Create(filePath)) // ho creato una variabile di processo a cui posso acedere solo dentro lo using { byte[] info = new UTF8Encoding(true).GetBytes("ciao!!! sto scrivendo in un file \n sono andata a capo"); //abbiamo bisogno di un array di byte; stiamo strasformando una stringa in una sequenza di byte //con UTF8 gli stiamo dicendo che stiamo usando i caratteri "latini(?) await file.WriteAsync(info, 0, info.Length); // file.Write() metodo sincrono file.Close(); //è buona norma dichiare di chiude la connessione using (StreamReader reader = File.OpenText(filePath)) //possiamo sare using uno dentro l'altro { //ex. per ogni linea possiamo leggere la linea e metterla a console. //Come capiamo quando ha finito? while (reader.Peek() > -1) // finchè il file non ha fine; il peek serve per segnare a che linea del file si è { Console.WriteLine("il file contiene: {0}", reader.ReadLine()); } } } } catch (Exception e) { Console.WriteLine(e.Message); } }
public static async Task <FileInfo> ToFile(this byte[] data, string path) { using var file = IOFile.Create(path); await file.WriteAsync(data, 0, data.Length).ConfigureAwait(false); return(new FileInfo(path)); }
public async Task <Stream> CreateFileAsync( string fileName, CancellationToken cancellationToken = default) { if (!Directory.Exists(_fullDirectoryPath)) { throw new DirectoryNotFoundException( $"The directory `{_fullDirectoryPath}` does not exist."); } string fullFilePath = Path.Combine(_fullDirectoryPath, fileName); if (IOFile.Exists(fullFilePath)) { throw new ArgumentException( $"File `{fullFilePath}` already exists.", nameof(fileName)); } return(await Task.Factory.StartNew( () => IOFile.Create(fullFilePath), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default) .ConfigureAwait(false)); }
private static async Task RestoreDatabaseAsync(string databaseName) { try { Stream stream = null; if (graphServiceClient == null) { var authResult = await InitializeWithSilentProviderAsync(); await InitializeGraphClientAsync(authResult); } var databasePath = await graphServiceClient.Me.Drive.Special.AppRoot.Children[databaseName].Request().GetAsync(); if (databasePath != null) { stream = await graphServiceClient.Me.Drive.Special.AppRoot.Children[databaseName].Content.Request().GetAsync(); var destinationPath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), databaseName)); using (var databaseDriveItem = File.Create(destinationPath)) { stream.Seek(0, SeekOrigin.Begin); await stream.CopyToAsync(databaseDriveItem); } } } catch (Exception exception) { await Dialogs.ExceptionDialogAsync(exception); } }
public void ReadsEventsFromRawBufferFiles() { using var tmp = new TempFolder(); var fn = tmp.AllocateFilename("json"); var lines = IOFile.ReadAllText(Path.Combine("Resources", "ThreeBufferedEvents.json.txt"), Encoding.UTF8).Split(new [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); using (var f = IOFile.Create(fn)) using (var fw = new StreamWriter(f, Encoding.UTF8)) { foreach (var line in lines) { fw.WriteLine(line); } } var position = new FileSetPosition(0, fn); var count = 0; var payload = PayloadReader.ReadPayload(1000, null, ref position, ref count, out var mimeType); Assert.Equal(SeqIngestionApi.RawEventFormatMediaType, mimeType); Assert.Equal(3, count); Assert.Equal(576 + 3 * (Environment.NewLine.Length - 1), position.NextLineStart); Assert.Equal(fn, position.File); var data = JsonConvert.DeserializeObject <dynamic>(payload); var events = data["Events"]; Assert.NotNull(events); Assert.Equal(3, events.Count); }
public async Task UploadProfileImage(IFormFile?file, CancellationToken cancellationToken) { if (file is null) { throw new BadRequestException(); } var userId = User.GetUserId(); var user = await _userManager.FindByIdAsync(userId.ToString()); if (user is null) { throw new ResourceNotFoundException(); } var profileImageName = Guid.NewGuid().ToString(); await using var fileStream = file.OpenReadStream(); Directory.CreateDirectory(_appSettings.Value.UserProfileImagePath); var path = Path.Combine($"{_appSettings.Value.UserProfileImagePath}\\{profileImageName}{Path.GetExtension(file.FileName)}"); await using var targetStream = SystemFile.Create(path); await fileStream.CopyToAsync(targetStream, cancellationToken); if (user.ProfileImageName is not null) { try { var filePath = Directory.GetFiles(_appSettings.Value.UserProfileImagePath, $"{user.ProfileImageName}.*").FirstOrDefault(); if (filePath != null) { SystemFile.Delete(filePath); } } catch { // not important } } try { user.ProfileImageName = profileImageName; await _userManager.UpdateAsync(user); } catch { SystemFile.Delete(path); throw; } }
/// <summary> /// Create an unregistered file handler /// </summary> /// <param name="filePath">string: full file path</param> /// <returns>IFile: file handler interface</returns> public static FileInfo CreateFile(string filePath) { if (!new FileInfo(filePath).Exists) { using (var sys = SysFile.Create(filePath)) { } } return(new FileInfo(filePath)); }
public void VersionCreated_FileAdded() { var createdfile = Path.Combine(_repository.Path, $"{Guid.NewGuid().ToString("n").Substring(0, 4)}.txt"); var stream = File.Create(createdfile); stream.Close(); _vm.CreateVersion(_repository); Assert.IsTrue(_vm.GetVersions(_repository).Last().Files.Count(f => f.State == State.New) >= 1); }
public EmitResult Compile(DocumentId documentId, string path) { var document = CurrentSolution.GetDocument(documentId); var compilation = document.Project.GetCompilationAsync().Result; using (var fileStream = File.Create(path)) { return(compilation.Emit(fileStream)); } }
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); }; }