Пример #1
0
 public void DescriptorClose()
 {
     using (var s = new NSFileHandle(0, false)) {
         // initWithFileDescriptor:closeOnDealloc: does not respond (see dontlink.app) but it works
         Assert.That(s.Handle, Is.Not.EqualTo(IntPtr.Zero), "Handle");
     }
 }
Пример #2
0
        partial void startStopPing(Foundation.NSObject sender)
        {
            if (task != null)
            {
                task.Interrupt();
            }
            else
            {
                task            = new NSTask();
                task.LaunchPath = "/sbin/ping";
                string[] args = { "-c10", hostField.StringValue };

                task.Arguments = args;

                // Create a new pipe
                pipe = new NSPipe();
                task.StandardOutput = pipe;

                NSFileHandle fh = pipe.ReadHandle;

                NSNotificationCenter nc = NSNotificationCenter.DefaultCenter;
                nc.RemoveObserver(this);
                nc.AddObserver(this, new Selector("dataReady:"), NSFileHandle.ReadCompletionNotification, fh);
                nc.AddObserver(this, new Selector("taskTerminated:"), NSTask.NSTaskDidTerminateNotification, task);
                task.Launch();
                outputView.Value = "";

                // Suspect = Obj-C example is [fh readInBackgroundAndNotify] - no arguments
                fh.ReadInBackground();
            }
        }
Пример #3
0
        public static string Method1()
        {
            string[] args = new string[] { "-rd1", "-c", "IOPlatformExpertDevice", "|", "grep", "model" };
            NSTask   task = new NSTask();

            task.LaunchPath = @"/usr/sbin/ioreg";
            task.Arguments  = args;

            NSPipe pipe = new NSPipe();

            task.StandardOutput = pipe;
            task.Launch();

            string[] args2 = new string[] { "/IOPlatformUUID/ { split($0, line, \"\\\"\"); printf(\"%s\\n\", line[4]); }" };

            NSTask task2 = new NSTask();

            task2.LaunchPath = @"/usr/bin/awk";
            task2.Arguments  = args2;

            NSPipe pipe2 = new NSPipe();

            task2.StandardInput  = pipe;
            task2.StandardOutput = pipe2;
            NSFileHandle fileHandle2 = pipe2.ReadHandle;

            task2.Launch();

            NSData   data = fileHandle2.ReadDataToEndOfFile();
            NSString uuid = NSString.FromData(data, NSStringEncoding.UTF8);

            return(uuid.ToString().Replace("\n", ""));
        }
        public string ReadFile(string path, string userIdentity)
        {
            string result = String.Empty;

            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                if (FileExists(path))
                {
                    NSFileHandle fileHandle = null;
                    NSError      error      = null;
                    Exception    exception  = null;

                    try
                    {
                        UIApplication.SharedApplication.InvokeOnMainThread(() =>
                        {
                            _fileProtectionManagerService.DecryptFile(path);
                            fileHandle = NSFileHandle.OpenReadUrl(NSUrl.CreateFileUrl(new[] { path }), out error);
                            if (fileHandle != null)
                            {
                                var nsStringResult = NSString.FromData(fileHandle.ReadDataToEndOfFile(), NSStringEncoding.UTF8);
                                if (nsStringResult != null)
                                {
                                    result = nsStringResult.ToString();
                                }
                            }
                            _fileProtectionManagerService.EncryptFile(path, userIdentity);
                        });
                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                    }
                    finally
                    {
                        if (fileHandle != null)
                        {
                            fileHandle.CloseFile();
                        }
                    }

                    if (error != null)
                    {
                        _loggingService.LogError(typeof(FileSystemService), new Exception(error.DebugDescription), error.Description);
                        throw new NSErrorException(error);
                    }
                    else if (exception != null)
                    {
                        _loggingService.LogError(typeof(FileSystemService), exception, exception.Message);
                        throw exception;
                    }
                }
            }

            return(result);
        }
        public Task <(bool, FileData)> GetFileDataFromPath(string filePath)
        {
            NSFileManager fileManager = NSFileManager.DefaultManager;

            if (fileManager.FileExists(filePath))
            {
                NSFileHandle nSFileHandle = NSFileHandle.OpenRead(filePath);
                var          fileData     = nSFileHandle.AvailableData();

                return(Task.FromResult((true, new FileData(filePath, Path.GetFileName(filePath), () => fileData.AsStream()))));
            }
            else
            {
                return(Task.FromResult <(bool, FileData)>((false, null)));
            }
        }
Пример #6
0
        public void ReadFile()
        {
            try
            {
                // Gets the direct path to the file
                NSString folderPath = dataPath.AppendPathComponent(new NSString("testfile.txt"));

                // Handle the data and read it from the specific path
                NSFileHandle nsfh = NSFileHandle.OpenRead(folderPath);

                // Gets the data from the file
                NSData data = nsfh.ReadDataToEndOfFile();

                string text = data.ToString();
            }
            catch (Exception ex)
            {
                // Failed read data from a file
            }
        }
        private Stream PlatformGetInputStream(string path)
        {
            if (FileExists(path))
            {
                NSFileHandle handle = NSFileHandle.OpenReadUrl(NSUrl.CreateFileUrl(new[] { path }), out NSError error);

                if (error != null)
                {
                    throw new NSErrorException(error);
                }
                else
                {
                    NSData result = handle.ReadDataToEndOfFile();
                    handle.CloseFile();
                    return result.AsStream();
                }
            }

            throw new FileNotFoundException();
        }
        private string PlatformReadFile(string path)
        {
            if (FileExists(path))
            {
                NSFileHandle handle = NSFileHandle.OpenReadUrl(NSUrl.CreateFileUrl(new[] { path }), out NSError error);

                if (error != null)
                {
                    throw new NSErrorException(error);
                }
                else
                {
                    NSString result = NSString.FromData(handle.ReadDataToEndOfFile(), NSStringEncoding.UTF8);
                    handle.CloseFile();
                    return result?.ToString() ?? "";
                }
            }

            throw new FileNotFoundException();
        }
Пример #9
0
        /// <summary>
        /// Clear logs. Reset the folder and file URL for later use.
        /// </summary>
        public void ClearLogs()
        {
            this.PerformBlockAndWait(() =>
            {
                this.fileHandle.CloseFile();
                this.fileHandle.Dispose();
                this.fileHandle = null;

                NSFileManager.DefaultManager.Remove(this.folderUrl, out NSError error);
                if (error != null)
                {
                    Console.WriteLine($"Failed to clear the log folder!\n{error.LocalizedDescription ?? string.Empty}");
                }

                // Create a new file handle.
                this.fileUrl    = null;
                this.folderUrl  = null;
                this.fileHandle = NSFileHandle.OpenUpdateUrl(this.FileUrl, out NSError urlError);
                System.Diagnostics.Debug.Assert(this.fileHandle != null, "Failed to create the file handle!");
            });
        }
        public Stream GetInputStream(string path, string userIdentity)
        {
            NSFileHandle fileHandle = null;
            NSError      error      = null;
            NSData       result     = null;
            Exception    exception  = null;

            try
            {
                UIApplication.SharedApplication.InvokeOnMainThread(() =>
                {
                    _fileProtectionManagerService.DecryptFile(path);
                    fileHandle = NSFileHandle.OpenReadUrl(NSUrl.CreateFileUrl(new[] { path }), out error);
                    result     = fileHandle.ReadDataToEndOfFile();
                    _fileProtectionManagerService.EncryptFile(path, userIdentity);
                });
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                if (fileHandle != null)
                {
                    fileHandle.CloseFile();
                }
            }

            if (error != null)
            {
                throw new NSErrorException(error);
            }
            else if (exception != null)
            {
                throw exception;
            }

            return(result?.AsStream() ?? null);
        }
Пример #11
0
        public override void ShellSyncCore(string path, string[] arguments, string autoWriteStdin, out string stdout, out string stderr, out int exitCode)
        {
            if (autoWriteStdin != "")
            {
                throw new Exception("ShellSyncCore::AutoWriteStdin not supported in macOS");                 // Never need yet, used only in Linux
            }
            try
            {
                var pipeOut = new NSPipe();
                var pipeErr = new NSPipe();

                var t = new NSTask();

                t.LaunchPath     = path;
                t.Arguments      = arguments;
                t.StandardOutput = pipeOut;
                t.StandardError  = pipeErr;

                t.Launch();
                t.WaitUntilExit();
                //t.Release();
                t.Dispose();

                NSFileHandle fileOut = pipeOut.ReadHandle;
                stdout = fileOut.ReadDataToEndOfFile().ToString();
                fileOut.CloseFile();

                NSFileHandle fileErr = pipeErr.ReadHandle;
                stderr = fileErr.ReadDataToEndOfFile().ToString();
                fileErr.CloseFile();

                exitCode = t.TerminationStatus;
            }
            catch (Exception ex)
            {
                stdout   = "";
                stderr   = "Error: " + ex.Message;
                exitCode = -1;
            }
        }
        private void PlatformWriteFile(string path, string contents)
        {
            if (FileExists(path))
            {
                NSFileHandle handle = NSFileHandle.OpenUpdateUrl(NSUrl.CreateFileUrl(new[] { path }), out NSError error);

                if (error != null)
                {
                    throw new NSErrorException(error);
                }
                else
                {
                    handle.SeekToEndOfFile();
                    handle.WriteData(NSData.FromString(contents));
                    handle.CloseFile();
                }
            }
            else
            {
                CreateFile(path, NSData.FromString(contents));
            }
        }
Пример #13
0
        public override void ShellSync(string path, string[] arguments, out string stdout, out string stderr, out int exitCode)
        {
            try
            {
                var pipeOut = new NSPipe();
                var pipeErr = new NSPipe();

                var t = new NSTask();

                t.LaunchPath     = path;
                t.Arguments      = arguments;
                t.StandardOutput = pipeOut;
                t.StandardError  = pipeErr;

                t.Launch();
                t.WaitUntilExit();
                //t.Release();
                t.Dispose();

                NSFileHandle fileOut = pipeOut.ReadHandle;
                stdout = fileOut.ReadDataToEndOfFile().ToString();
                fileOut.CloseFile();

                NSFileHandle fileErr = pipeErr.ReadHandle;
                stderr = fileErr.ReadDataToEndOfFile().ToString();
                fileErr.CloseFile();

                exitCode = t.TerminationStatus;
            }
            catch (Exception ex)
            {
                stdout   = "";
                stderr   = "Error: " + ex.Message;
                exitCode = -1;
            }
        }
Пример #14
0
        public void WriteFile()
        {
            try
            {
                // Gets the direct path to the file
                NSString folderPath = dataPath.AppendPathComponent(new NSString("testfile.txt"));

                // The text who should be written
                NSString someText = new NSString("Test");

                // The data
                NSData data = someText.Encode(NSStringEncoding.UTF8);

                // Handle the data and writes it to the specific path
                NSFileHandle nsfh = NSFileHandle.OpenWrite(folderPath);

                // Writes the data
                nsfh.WriteData(data);
            }
            catch (Exception ex)
            {
                // Failed write data into a file
            }
        }
        public void WriteFile(string path, string userIdentity, string contents)
        {
            if (!string.IsNullOrEmpty(path) || !string.IsNullOrEmpty(contents))
            {
                if (!NSFileManager.DefaultManager.FileExists(path))
                {
                    var dict = new NSMutableDictionary();
                    UIApplication.SharedApplication.InvokeOnMainThread(() =>
                    {
                        NSFileManager.DefaultManager.CreateFile(path, NSData.FromString(contents), dict);
                    });
                    _fileProtectionManagerService.ProtectFile(path, userIdentity);
                    _fileProtectionManagerService.EncryptFile(path, userIdentity);
                }
                else
                {
                    NSFileHandle fileHandle = null;
                    NSError      error      = null;
                    Exception    exception  = null;

                    try
                    {
                        UIApplication.SharedApplication.InvokeOnMainThread(() =>
                        {
                            _fileProtectionManagerService.DecryptFile(path);
                            fileHandle = NSFileHandle.OpenUpdateUrl(NSUrl.CreateFileUrl(new[] { path }), out error);
                            fileHandle.SeekToEndOfFile();
                            fileHandle.WriteData(NSData.FromString(contents));

                            _fileProtectionManagerService.ProtectFile(path, userIdentity);
                            _fileProtectionManagerService.EncryptFile(path, userIdentity);
                        });
                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                    }
                    finally
                    {
                        if (fileHandle != null)
                        {
                            UIApplication.SharedApplication.InvokeOnMainThread(() =>
                            {
                                fileHandle.CloseFile();
                            });
                        }
                    }

                    if (error != null)
                    {
                        _loggingService.LogError(typeof(FileSystemService), new Exception(error.DebugDescription), error.Description);
                        throw new NSErrorException(error);
                    }
                    else if (exception != null)
                    {
                        _loggingService.LogError(typeof(FileSystemService), exception, exception.Message);
                        throw exception;
                    }
                }
            }
        }
Пример #16
0
 private Logger()
 {
     this.fileHandle = NSFileHandle.OpenUpdateUrl(this.FileUrl, out NSError error);
     System.Diagnostics.Debug.Assert(this.fileHandle != null, "Failed to create the file handle!");
 }
        public Stream OpenRead(string filePath)
        {
            var path = filePath.Replace("\\", "/");

            return(NSFileHandle.OpenRead(path).ReadDataToEndOfFile().AsStream());
        }