예제 #1
0
        public static uint Read(this IStream stream, byte[] buffer)
        {
            uint written = 0;

            stream.Read(buffer, buffer.Length, Pointer <uint> .AsPointer(ref written));
            return(written);
        }
예제 #2
0
        public void ThreadRun()
        {
            try
            {
                m_stream.Start(Convert.ToInt32(wavDataProvider.SampleRate));
                int nSamples = Convert.ToInt32(wavDataProvider.SampleRate / 50);
                do
                {
                    System.Runtime.InteropServices.ComTypes.IStream strm = wavDataProvider.GetNextAudioChunk(nSamples);
                    if (null == strm)
                    {
                        break;
                    }
                    while (false == PushSamples(strm))
                    {
                        Thread.Sleep(20);
                    }

                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(strm);
                    strm = null;
                } while (wavDataProvider.HasMoreData);
            }
            catch (COMException)
            {
            }
            m_stream.Stop();
            AllDataWritten.Invoke(this, null);
        }
예제 #3
0
파일: MsgHelper.cs 프로젝트: alex765022/IBN
        void readStream(System.Runtime.InteropServices.ComTypes.IStream ppstm, MemoryStream dest)
        {
            int size = 0;

            System.Runtime.InteropServices.ComTypes.STATSTG statstgstream;
            ppstm.Stat(out statstgstream, 1);
            size = (int)statstgstream.cbSize;

            IntPtr pm = new IntPtr();

            byte[] buffer = new byte[1024];
            int    page   = 1024;

            while (size > 0)
            {
                if (size < page)
                {
                    page = size;
                }

                ppstm.Read(buffer, page, pm);
                dest.Write(buffer, 0, page);

                size -= page;
            }
        }
        public void Load(IStream pStm)
        {
            System.Runtime.InteropServices.ComTypes.IStream stream = (System.Runtime.InteropServices.ComTypes.IStream)pStm;

            //load the information from the stream
            object obj = null;

            obj       = PeristStream.PeristStreamHelper.Load(stream);
            m_version = Convert.ToInt32(obj);

            obj = PeristStream.PeristStreamHelper.Load(stream);
            byte[] arr = (byte[])obj;
            m_ID = new Guid(arr);

            obj    = PeristStream.PeristStreamHelper.Load(stream);
            m_name = Convert.ToString(obj);

            obj          = PeristStream.PeristStreamHelper.Load(stream);
            m_spatialRef = obj as ISpatialReference;

            obj  = PeristStream.PeristStreamHelper.Load(stream);
            m_ID = (Guid)obj;

            obj     = PeristStream.PeristStreamHelper.Load(stream);
            m_point = obj as IPoint;

            obj   = PeristStream.PeristStreamHelper.Load(stream);
            m_arr = obj as ArrayList;
        }
        public void Save(IStream pStm, int fClearDirty)
        {
            System.Runtime.InteropServices.ComTypes.IStream stream = (System.Runtime.InteropServices.ComTypes.IStream)pStm;

            //save the different objects to the stream
            PeristStream.PeristStreamHelper.Save(stream, m_version);
            PeristStream.PeristStreamHelper.Save(stream, m_ID.ToByteArray());
            PeristStream.PeristStreamHelper.Save(stream, m_name);
            PeristStream.PeristStreamHelper.Save(stream, m_spatialRef);

            //save the guid
            PeristStream.PeristStreamHelper.Save(stream, m_ID);

            //save the point to the stream
            if (null == m_point)
            {
                m_point = new PointClass();
            }

            PeristStream.PeristStreamHelper.Save(stream, m_point);

            if (null == m_arr)
            {
                m_arr = new ArrayList();
            }

            PeristStream.PeristStreamHelper.Save(stream, m_arr);
        }
예제 #6
0
        /// <summary>
        /// 加文件,完全看不懂啊
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        private bool AddFile(ref IFsiDirectoryItem root)
        {
            System.Runtime.InteropServices.ComTypes.IStream stream = null;
            try
            {
                Win32.SHCreateStreamOnFile(m_strThisPath, Win32.STGM_READ | Win32.STGM_SHARE_DENY_WRITE,
                                           ref stream);

                if (stream != null)
                {
                    root.AddFile(m_strDisplayName, stream);
                    return(true);
                }
                return(true);
            }
            catch (System.Exception ex)
            {
                return(false);
            }
            finally
            {
                if (stream != null)
                {
                    Marshal.FinalReleaseComObject(stream);
                }
            }
        }
 void ZelloPTTLib.IAudioStream.WriteSamples(object vData)
 {
     byte[] arr;
     try
     {
         System.Runtime.InteropServices.ComTypes.IStream comStream = vData as System.Runtime.InteropServices.ComTypes.IStream;
         if (comStream != null)
         {
             System.Runtime.InteropServices.ComTypes.STATSTG stg;
             comStream.Stat(out stg, 1 /*STATFLAG_NONAME*/);
             long lSize = stg.cbSize;
             sampleCount += Convert.ToInt32(lSize / 2);
             arr          = new byte[lSize];
             IntPtr pInt = (IntPtr)0;
             comStream.Read(arr, Convert.ToInt32(lSize), pInt);
             foreach (IAudioStreamSink sink in lstSinks)
             {
                 sink.onAudioData(arr);
             }
             System.Runtime.InteropServices.Marshal.FinalReleaseComObject(comStream);
             comStream = null;
         }
     }
     catch (System.Exception _ex)
     {
         System.Diagnostics.Debug.WriteLine("Exception in AudioStreamImpl.WriteSamples : " + _ex.Message);
     }
 }
예제 #8
0
        public bool CopyFileFromDevice(string sourceName, string destinationName)
        {
            PortableDeviceFile file;



            file = GetFile(sourceName);

            if (file != null)
            {
                IPortableDeviceResources resources;
                file.content.Transfer(out resources);
                file.parentDevice.Connect();
                PortableDeviceApiLib.IStream wpdStream;
                uint optimalTransferSize = 0;

                resources.GetStream(file.Id, ref PortableDeviceConstants.WPD_RESOURCE_DEFAULT, PortableDeviceConstants.STGM_READ, ref optimalTransferSize, out wpdStream);

                System.Runtime.InteropServices.ComTypes.IStream sourceStream = (System.Runtime.InteropServices.ComTypes.IStream)wpdStream;


                FileStream targetStream = new FileStream(destinationName, FileMode.Create, FileAccess.Write);

                if (targetStream != null)
                {
                    IntPtr pBytsRead = Marshal.AllocHGlobal(4);

                    byte[] buffer = new byte[1024];

                    int bytesRead;

                    do
                    {
                        sourceStream.Read(buffer, 1024, pBytsRead);

                        bytesRead = Marshal.ReadInt32(pBytsRead);
                        targetStream.Write(buffer, 0, bytesRead);
                    } while (bytesRead > 0);


                    Marshal.FreeHGlobal(pBytsRead);

                    targetStream.Close();
                    file.parentDevice.Disconnect();

                    return(true);
                }
                else
                {
                    throw new Exception("Unable to open destination file for writing");
                }
            }
            else
            {
                throw new Exception("File does not exist");
            }

            return(false);
        }
예제 #9
0
        public static uint Write <T>(this IStream stream, T obj)
        {
            var ptr = Pointer <T> .AsPointer(ref obj);

            byte[] buffer = new byte[Pointer <T> .TypeSize()];
            Marshal.Copy(ptr, buffer, 0, buffer.Length);
            return(stream.Write(buffer));
        }
예제 #10
0
        private static string TransferContentFromDevice(string saveToPath, IPortableDeviceContent content, string parentObjectID)
        {
            IPortableDeviceResources resources;

            content.Transfer(out resources);
            PortableDeviceApiLib.IStream wpdStream = null;
            uint optimalTransferSize = int.MaxValue;

            PortableDeviceApiLib._tagpropertykey property = new PortableDeviceApiLib._tagpropertykey();
            property.fmtid = new Guid(0xE81E79BE, 0x34F0, 0x41BF, 0xB5, 0x3F, 0xF1, 0xA0, 0x6A, 0xE8, 0x78, 0x42);
            property.pid   = 0;

            try
            {
                resources.GetStream(parentObjectID, ref property, 0, ref optimalTransferSize, out wpdStream);
                System.Runtime.InteropServices.ComTypes.IStream sourceStream = (System.Runtime.InteropServices.ComTypes.IStream)wpdStream;

                using (FileStream targetStream = new FileStream(saveToPath, FileMode.Create, FileAccess.Write))
                {
                    int    filesize        = int.Parse(optimalTransferSize.ToString());
                    var    buffer          = new byte[filesize];
                    int    bytesRead       = 0;
                    IntPtr bytesReadIntPtr = new IntPtr(bytesRead);
                    //设备建议读取长度optimalTransferSize长度一般为262144即256k,
                    //注释掉的sourceStream.Read不能更新bytesRead值,do循环只能执行一次即写入256k数据。
                    //创建nextBufferSize变量,用于每次Read后计算下一次buffer长度
                    int nextBufferSize = 0;
                    do
                    {
                        if (bytesReadIntPtr == IntPtr.Zero)
                        {
                            bytesReadIntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int)));
                        }
                        sourceStream.Read(buffer, filesize, bytesReadIntPtr);
                        nextBufferSize = Marshal.ReadInt32(bytesReadIntPtr);
                        if (filesize > nextBufferSize)
                        {
                            filesize = nextBufferSize;
                        }

                        targetStream.Write(buffer, 0, filesize);
                    } while (nextBufferSize > 0);
                    Marshal.FreeCoTaskMem(bytesReadIntPtr);
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            finally
            {
                if (wpdStream != null)
                {
                    Marshal.ReleaseComObject(wpdStream);
                }
            }
            return(string.Empty);
        }
예제 #11
0
        /// <summary>
        /// Enumerates an Interop.IStorage object and creates the internal file object collection
        /// </summary>
        /// <param name="BasePath">Sets the base url for the storage files</param>
        /// <param name="enumStorage">storage to enumerate</param>
        protected void EnumIStorageObject(Interop.IStorage enumStorage, string BasePath)
        {
            Interop.IEnumSTATSTG iEnumSTATSTG;

            System.Runtime.InteropServices.ComTypes.STATSTG sTATSTG;

            int i;

            enumStorage.EnumElements(0, IntPtr.Zero, 0, out iEnumSTATSTG);
            iEnumSTATSTG.Reset();
            while (iEnumSTATSTG.Next(1, out sTATSTG, out i) == (int)Interop.S_OK)
            {
                if (i == 0)
                {
                    break;
                }

                FileObject newFileObj = new FileObject();
                newFileObj.FileType = sTATSTG.type;
                switch (sTATSTG.type)
                {
                case 1:
                    Interop.IStorage iStorage = enumStorage.OpenStorage(sTATSTG.pwcsName, IntPtr.Zero, 16, IntPtr.Zero, 0);
                    if (iStorage != null)
                    {
                        string str = String.Concat(BasePath, sTATSTG.pwcsName.ToString());
                        newFileObj.FileStorage = iStorage;
                        newFileObj.FilePath    = BasePath;
                        newFileObj.FileName    = sTATSTG.pwcsName.ToString();
                        foCollection.Add(newFileObj);
                        EnumIStorageObject(iStorage, str);
                    }
                    break;

                case 2:
                    System.Runtime.InteropServices.ComTypes.IStream uCOMIStream = enumStorage.OpenStream(sTATSTG.pwcsName, IntPtr.Zero, 16, 0);
                    newFileObj.FilePath   = BasePath;
                    newFileObj.FileName   = sTATSTG.pwcsName.ToString();
                    newFileObj.FileStream = uCOMIStream;
                    foCollection.Add(newFileObj);
                    break;

                case 4:
                    Debug.WriteLine("Ignoring IProperty type ...");
                    break;

                case 3:
                    Debug.WriteLine("Ignoring ILockBytes type ...");
                    break;

                default:
                    Debug.WriteLine("Unknown object type ...");
                    break;
                }
            }
        }
예제 #12
0
        public byte[] Read(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            var mtpDevice = MtpDeviceManager.GetPortableDevice(path);

            if (!Exists(path))
            {
                throw new ArgumentException("Path does not exist.");
            }

            var mtpFile = mtpDevice.GetObject(path.Replace(MtpPathInterpreter.GetMtpDeviceName(path), string.Empty)) as PortableDeviceFile;

            if (mtpFile == null)
            {
                mtpDevice.Disconnect();
                throw new IOException("Path not accessible.");
            }


            IPortableDeviceResources resources;

            mtpDevice.Content.Transfer(out resources);

            PortableDeviceApiLib.IStream wpdStream;
            uint optimalTransferSize = 0;

            resources.GetStream(mtpFile.Id, ref PortableDevicePKeys.WPD_RESOURCE_DEFAULT, 0, ref optimalTransferSize, out wpdStream);

            System.Runtime.InteropServices.ComTypes.IStream sourceStream = (System.Runtime.InteropServices.ComTypes.IStream)wpdStream;

            MemoryStream targetStream = new MemoryStream();

            unsafe
            {
                var buffer = new byte[1024];
                int bytesRead;
                do
                {
                    sourceStream.Read(buffer, 1024, new IntPtr(&bytesRead));
                    targetStream.Write(buffer, 0, bytesRead);
                } while (bytesRead > 0);
            }
            var len = targetStream.Length;

            byte[] result = new byte[len];
            targetStream.Position = 0;
            targetStream.Read(result, 0, (int)len);
            targetStream.Close();
            resources.Cancel();
            mtpDevice.Disconnect();
            return(result);
        }
예제 #13
0
 /// <summary>
 /// Closes the storage stream
 /// </summary>
 public override void Close()
 {
     if (fileStream != null)
     {
         fileStream.Commit(0);
         Marshal.ReleaseComObject(fileStream);
         fileStream = null;
         GC.SuppressFinalize(this);
     }
 }
예제 #14
0
 public void UpdateModuleSymbols(IntPtr pAppDomain, IntPtr pModule, System.Runtime.InteropServices.ComTypes.IStream pSymbolStream)
 {
     Call(delegate
     {
         _managedCallback.UpdateModuleSymbols(
             _connector.MarshalAs <ICorDebugAppDomain>(pAppDomain),
             _connector.MarshalAs <ICorDebugModule>(pModule),
             pSymbolStream);
     });
 }
예제 #15
0
        public static uint Read <T>(this IStream stream, ref T obj)
        {
            var ptr = Pointer <T> .AsPointer(ref obj);

            byte[] buffer  = new byte[Pointer <T> .TypeSize()];
            uint   written = stream.Read(buffer);

            Marshal.Copy(buffer, 0, ptr, buffer.Length);
            return(written);
        }
예제 #16
0
            public void Clone(out System.Runtime.InteropServices.ComTypes.IStream ppstm)
            {
                IStreamContainer clone = new IStreamContainer(new MemoryStream((int)this.stream.Length));
                var p = this.stream.Position;

                this.stream.Position = 0;
                this.stream.CopyTo(clone.stream);
                clone.stream.Position = this.stream.Position = p;
                ppstm = clone;
            }
예제 #17
0
파일: MsgHelper.cs 프로젝트: alex765022/IBN
        System.Runtime.InteropServices.ComTypes.IStream getStream(string header)
        {
            System.Runtime.InteropServices.ComTypes.IStream ppstm = null;
            strge.OpenStream(header,
                             IntPtr.Zero,
                             NativeCalls.STGM_READWRITE | NativeCalls.STGM_SHARE_EXCLUSIVE,
                             (uint)0,
                             out ppstm);

            return(ppstm);
        }
예제 #18
0
        private void DownloadFile(TransFileObject file, string destPath, IPortableDeviceContent content)
        {
            IPortableDeviceProperties properties;

            content.Properties(out properties);

            var downloadFileObj = WrapObject(properties, file.objId);

            IPortableDeviceResources resources;

            content.Transfer(out resources);

            PortableDeviceApiLib.IStream wpdStream;
            uint optimalTransferSize = 0;

            var property = new _tagpropertykey();

            property.fmtid = new Guid(0xE81E79BE, 0x34F0, 0x41BF, 0xB5, 0x3F, 0xF1, 0xA0, 0x6A, 0xE8, 0x78, 0x42);
            property.pid   = 0;

            resources.GetStream(file.objId, ref property, 0, ref optimalTransferSize, out wpdStream);
            System.Runtime.InteropServices.ComTypes.IStream sourceStream = (System.Runtime.InteropServices.ComTypes.IStream)wpdStream;

            FileStream targetStream = new FileStream(destPath, FileMode.Create, FileAccess.Write);

            unsafe {
                var buffer = new byte[10240];
                int bytesRead;
                do
                {
                    sourceStream.Read(buffer, 10240, new IntPtr(&bytesRead));
                    if (bytesRead <= 0)
                    {
                        break;
                    }
                    targetStream.Write(buffer, 0, bytesRead);
                } while (true /*bytesRead > 0*/);

                targetStream.Close();
            }

            Marshal.ReleaseComObject(sourceStream);
            Marshal.ReleaseComObject(wpdStream);


            // ファイルの更新日時を更新
            DateTime setDate = file.updateTime;

            if (setDate.CompareTo(DateTime.MinValue) == 0)
            {
                setDate = GetImgTakenDate(destPath);  // Exifから撮影日時情報を取得
            }
            File.SetLastWriteTime(destPath, setDate);
        }
예제 #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ComStreamWrapper"/> class.
        /// </summary>
        /// <param name="istream">The istream to wrap.</param>
        /// <param name="isStreamOwner">If set to <c>true</c>, this instance should be the owner of the wrapped stream and thus is responsible for disposing it.</param>
        /// <exception cref="System.ArgumentNullException">istream is null.</exception>
        public ComStreamWrapper(System.Runtime.InteropServices.ComTypes.IStream istream, bool isStreamOwner)
        {
            _istream       = istream ?? throw new ArgumentNullException(nameof(istream));
            _isStreamOwner = isStreamOwner;

            _int64Ptr = Marshal.AllocCoTaskMem(8);
            _int32Ptr = Marshal.AllocCoTaskMem(4);

            _streamStatus = new System.Runtime.InteropServices.ComTypes.STATSTG();
            _istream.Stat(out _streamStatus, STATFLAG.NONAME);
        }
예제 #20
0
        /// <summary>
        /// This method copies the file from the device to the destination path.
        /// </summary>
        /// <param name="destinationPath"></param>
        private void TransferFile(string destinationPath)
        {
            // TODO: Clean this up.

            IPortableDeviceResources resources;

            DeviceContent.Transfer(out resources);

            IStream wpdStream           = null;
            uint    optimalTransferSize = 0;

            var property = new _tagpropertykey
            {
                fmtid = new Guid("E81E79BE-34F0-41BF-B53F-F1A06AE87842"),
                pid   = 0
            };

            System.Runtime.InteropServices.ComTypes.IStream sourceStream = null;
            try
            {
                resources.GetStream(Id, ref property, 0, ref optimalTransferSize, out wpdStream);
                sourceStream = (System.Runtime.InteropServices.ComTypes.IStream)wpdStream;

                FileStream targetStream = new FileStream(
                    Path.Combine(destinationPath, OriginalFileName.Value),
                    FileMode.Create,
                    FileAccess.Write);

                unsafe
                {
                    try
                    {
                        var buffer = new byte[1024];
                        int bytesRead;
                        do
                        {
                            sourceStream.Read(buffer, 1024, new IntPtr(&bytesRead));
                            targetStream.Write(buffer, 0, bytesRead);
                        } while (bytesRead > 0);
                    }
                    finally
                    {
                        targetStream.Close();
                    }
                }
            }
            finally
            {
                Marshal.ReleaseComObject(sourceStream);
                Marshal.ReleaseComObject(wpdStream);
            }
        }
예제 #21
0
        public Stream OpenRead()
        {
            IPortableDeviceResources res;

            _content.Transfer(out res);

            uint    size = 0;
            IStream stream;

            res.GetStream(ContentID, ref WPDConstants.PortableDevicePKeys.WPD_RESOURCE_DEFAULT, 0, ref size, out stream);
            System.Runtime.InteropServices.ComTypes.IStream istream = (System.Runtime.InteropServices.ComTypes.IStream)stream;
            return(new ComIStreamWrapper(istream));
        }
예제 #22
0
        public void Initialize(IStream pIStream, WICDecodeOptions cacheOptions)
        {
            Log.Trace("Initialize called");

            lock (this)
            {
                frame  = null;
                stream = new WICReadOnlyStreamWrapper(pIStream);

                ReadExif();
            }
            Log.Trace("Initialize finished");
        }
예제 #23
0
        //   uint tmpBufferSize = 0;
        //   uint tmpTransferSize = 0;
        //   string tmpTransferContext = string.Empty;
        //   {
        //     pResults.GetStringValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, out tmpTransferContext);
        //     pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_TOTAL_DATA_SIZE, out tmpBufferSize);
        //     pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPTIMAL_TRANSFER_BUFFER_SIZE, out tmpTransferSize);

        //     try
        //     {
        //       int pValue;
        //       pResults.GetErrorValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out pValue);
        //       if(pValue!=0)
        //       {
        //         return null;
        //       }
        //     }
        //     catch
        //     {
        //     }
        //   }

        //   pParameters.Clear();
        //   pResults.Clear();

        //   byte[] tmpData = new byte[(int)tmpTransferSize];
        //   //CCustomReadContext{81CD75F1-A997-4DA2-BAB1-FF5EC514E355}
        //   pParameters.SetGuidValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_READ_DATA.fmtid);
        //   pParameters.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_ID, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_READ_DATA.pid);
        //   pParameters.SetStringValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, tmpTransferContext);
        //   pParameters.SetBufferValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, ref tmpData[0], (uint)tmpTransferSize);
        //   pParameters.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_NUM_BYTES_TO_READ, (uint)tmpTransferSize);
        //   pParameters.SetIPortableDevicePropVariantCollectionValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_OPERATION_PARAMS, propVariant);


        //   portableDeviceClass.SendCommand(0, pParameters, out pResults);


        //   uint cbBytesRead = 0;

        //   try
        //   {
        //     int pValue = 0;
        //     pResults.GetErrorValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out pValue);
        //     if (pValue != 0)
        //       return null;
        //   }
        //   catch(Exception ex)
        //   {
        //   }
        //   // 24,142,174,9
        //   // 18, 8E
        //   GCHandle pinnedArray = GCHandle.Alloc(imgdate, GCHandleType.Pinned);
        //   IntPtr ptr = pinnedArray.AddrOfPinnedObject();

        //   uint dataread =0;
        //   pResults.GetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_NUM_BYTES_READ, out dataread);
        //   pResults.GetBufferValue(ref PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_DATA, ptr, out cbBytesRead);

        //   IntPtr tmpPtr = new IntPtr(Marshal.ReadInt64(ptr));
        //   byte[] res = new byte[(int)cbBytesRead];
        //   for (int i = 0; i < cbBytesRead; i++)
        //   {
        //     res[i] = Marshal.ReadByte(tmpPtr, i);
        //   }

        //   pParameters.Clear();
        //   pResults.Clear();
        //   {
        //     pParameters.SetGuidValue(PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_CATEGORY, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_END_DATA_TRANSFER.fmtid);
        //     pParameters.SetUnsignedIntegerValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_COMMAND_ID, PortableDevicePKeys.WPD_COMMAND_MTP_EXT_END_DATA_TRANSFER.pid);
        //     pParameters.SetStringValue(PortableDevicePKeys.WPD_PROPERTY_MTP_EXT_TRANSFER_CONTEXT, tmpTransferContext);
        //   }

        //   portableDeviceClass.SendCommand(0, pParameters, out pResults);

        //   Marshal.FreeHGlobal(tmpPtr);
        //   pinnedArray.Free();
        //   //Marshal.FreeHGlobal(ptr);

        //   try
        //   {
        //     int tmpResult = 0;

        //     pResults.GetErrorValue(ref PortableDevicePKeys.WPD_PROPERTY_COMMON_HRESULT, out tmpResult);
        //     if(tmpResult!=0)
        //     {

        //     }
        //   }
        //   catch
        //   {
        //   }
        //   return res;
        //}

        /// <summary>
        /// Transfer from device to computer
        /// Source : http://cgeers.com/2011/08/13/wpd-transferring-content/
        /// </summary>
        /// <param name="deviceObject"></param>
        /// <param name="fileName"></param>
        public void SaveFile(PortableDeviceObject deviceObject, string fileName)
        {
            IPortableDeviceContent content;

            portableDeviceClass.Content(out content);
            IPortableDeviceResources resources;

            content.Transfer(out resources);

            PortableDeviceApiLib.IStream wpdStream = null;
            uint optimalTransferSize = 0;

            var property = PortableDevicePKeys.WPD_RESOURCE_DEFAULT;


            try
            {
                resources.GetStream(deviceObject.ID, ref property, 0, ref optimalTransferSize,
                                    out wpdStream);
            }
            catch (COMException comException)
            {
                // check if the device is busy, this may hapen when a another transfer not finished
                if ((uint)comException.ErrorCode == PortableDeviceErrorCodes.ERROR_BUSY)
                {
                    Thread.Sleep(500);
                    SaveFile(deviceObject, fileName);
                    return;
                }
                throw comException;
            }

            System.Runtime.InteropServices.ComTypes.IStream sourceStream =
                (System.Runtime.InteropServices.ComTypes.IStream)wpdStream;

            FileStream targetStream = new FileStream(fileName,
                                                     FileMode.Create, FileAccess.Write);

            unsafe
            {
                var buffer = new byte[1024 * 256];
                int bytesRead;
                do
                {
                    sourceStream.Read(buffer, buffer.Length, new IntPtr(&bytesRead));
                    targetStream.Write(buffer, 0, bytesRead);
                } while (bytesRead > 0);

                targetStream.Close();
            }
        }
예제 #24
0
		/// <summary>
		/// Initializes a new instance of the <see cref="ComStreamWrapper"/> class.
		/// </summary>
		/// <param name="istream">The istream to wrap.</param>
		/// <param name="isStreamOwner">If set to <c>true</c>, this instance should be the owner of the wrapped stream and thus is responsible for disposing it.</param>
		/// <exception cref="System.ArgumentNullException">istream is null.</exception>
		public ComStreamWrapper(System.Runtime.InteropServices.ComTypes.IStream istream, bool isStreamOwner)
		{
			if (null == istream)
				throw new ArgumentNullException("istream");

			_isStreamOwner = isStreamOwner;
			_istream = istream;

			_int64Ptr = Marshal.AllocCoTaskMem(8);
			_int32Ptr = Marshal.AllocCoTaskMem(4);

			_streamStatus = new System.Runtime.InteropServices.ComTypes.STATSTG();
			_istream.Stat(out _streamStatus, STATFLAG.NONAME);
		}
예제 #25
0
 public SymbolWriterClass(EnCManager manager,ITokenTranslator transl)
 {
     // Create the writer from the COM catalog
     Type writerType = Type.GetTypeFromCLSID(typeof(CorSymWriter_SxSClass).GUID);
     object comWriterObj = Activator.CreateInstance(writerType);
     Type readerType = Type.GetTypeFromCLSID(typeof(CorSymReader_SxSClass).GUID);
     object comReaderObj = Activator.CreateInstance(readerType);
     mWriter = (ISymUnmanagedWriter2)comWriterObj;
     mReader = (ISymUnmanagedReader)comReaderObj;
     this.manager = manager;
     this.stream = new CorMemStream();
     this.translator = transl;
     State = WriterState.NotIninitialized;
 }
예제 #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (istream != null)
            {
                System.Runtime.InteropServices.ComTypes.IStream i = (System.Runtime.InteropServices.ComTypes.IStream)istream.Stream;
                System.Runtime.InteropServices.ComTypes.STATSTG st;
                i.Stat(out st, 0);

                byte[] buffer = new byte[st.cbSize];
                IntPtr ptr    = Marshal.AllocHGlobal(sizeof(int));
                i.Read(buffer, (int)st.cbSize, ptr);
                OnTestEvent("Size=" + st.cbSize.ToString() + "; read:" + Marshal.ReadIntPtr(ptr).ToString() + " bytes, starting:" + buffer[0].ToString("X"));
            }
        }
예제 #27
0
파일: MsgHelper.cs 프로젝트: alex765022/IBN
        protected void SetUTF(string key, uint keyValue, string value)
        {
            System.Runtime.InteropServices.ComTypes.IStream ppstm = getStream(key);
            IntPtr pm = new IntPtr();

            byte[] p = Encoding.UTF8.GetBytes(value);

            ppstm.Write(p, p.Length, pm);
            ppstm.SetSize(p.Length);

            ppstm.Commit(0);
            Marshal.ReleaseComObject(ppstm);

            modifyProperty(keyValue, p.Length + 1);
        }
예제 #28
0
파일: MsgHelper.cs 프로젝트: alex765022/IBN
        public void Commit()
        {
            System.Runtime.InteropServices.ComTypes.IStream ppstm = getStream("__properties_version1.0");
            IntPtr pm = new IntPtr();

            byte[] p = properties.ToArray();

            ppstm.Write(p, p.Length, pm);
            ppstm.Commit(0);

            strge.Commit(0);

            properties.Close();
            properties = null;
        }
예제 #29
0
        public SymbolWriterClass(EnCManager manager, ITokenTranslator transl)
        {
            // Create the writer from the COM catalog
            Type   writerType   = Type.GetTypeFromCLSID(typeof(CorSymWriter_SxSClass).GUID);
            object comWriterObj = Activator.CreateInstance(writerType);
            Type   readerType   = Type.GetTypeFromCLSID(typeof(CorSymReader_SxSClass).GUID);
            object comReaderObj = Activator.CreateInstance(readerType);

            mWriter         = (ISymUnmanagedWriter2)comWriterObj;
            mReader         = (ISymUnmanagedReader)comReaderObj;
            this.manager    = manager;
            this.stream     = new CorMemStream();
            this.translator = transl;
            State           = WriterState.NotIninitialized;
        }
예제 #30
0
        public void TransferContentToDevice(string fileName, string parentObjectId)
        {
            IPortableDeviceContent content;

            this._device.Content(out content);

            IPortableDeviceValues values =
                GetRequiredPropertiesForContentType(fileName, parentObjectId);

            PortableDeviceApiLib.IStream tempStream;
            uint optimalTransferSizeBytes = 0;

            content.CreateObjectWithPropertiesAndData(
                values,
                out tempStream,
                ref optimalTransferSizeBytes,
                null);

            System.Runtime.InteropServices.ComTypes.IStream targetStream =
                (System.Runtime.InteropServices.ComTypes.IStream)tempStream;
            try {
                using (var sourceStream =
                           new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
                    var buffer = new byte[optimalTransferSizeBytes];
                    int bytesRead;
                    do
                    {
                        bytesRead = sourceStream.Read(
                            buffer, 0, (int)optimalTransferSizeBytes);
                        IntPtr pcbWritten = IntPtr.Zero;
                        if (bytesRead < (int)optimalTransferSizeBytes)
                        {
                            targetStream.Write(buffer, bytesRead, pcbWritten);
                        }
                        else
                        {
                            targetStream.Write(buffer, (int)optimalTransferSizeBytes, pcbWritten);
                        }

                        /*targetStream.Write(
                         *      buffer, (int)optimalTransferSizeBytes, pcbWritten);*/
                    } while (bytesRead > 0);
                }
                targetStream.Commit(0);
            } finally {
                Marshal.ReleaseComObject(tempStream);
            }
        }
예제 #31
0
        void IInitializeWithStream.Initialize(System.Runtime.InteropServices.ComTypes.IStream stream, Shell.AccessModes fileMode)
        {
            var preview = this as IPreviewFromStream;

            if (preview == null)
            {
                throw new InvalidOperationException(
                          string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                        LocalizedMessages.PreviewHandlerUnsupportedInterfaceCalled,
                                        "IPreviewFromStream"));
            }
            using (var storageStream = new StorageStream(stream, fileMode != Shell.AccessModes.ReadWrite))
            {
                preview.Load(storageStream);
            }
        }
예제 #32
0
        public override void Close()
        {
            if (null != _istream)
            {
                //_istream.Commit(0);
                if (_isStreamOwner)
                {
                    Marshal.ReleaseComObject(_istream);
                    ComDebug.ReportInfo("ComStreamWrapper.Close: istream released");

                    ReportDebugStream("StreamWrapper.Close");
                }
                _istream = null;
            }
            base.Close();
        }
예제 #33
0
 void IStream.CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten)
 {
     throw new NotSupportedException();
 }
예제 #34
0
 void IStream.Clone(out IStream ppstm)
 {
     ppstm = null;
     throw new NotSupportedException();
 }
예제 #35
0
		/// <summary>
		/// Releases the unmanaged resources used by the <see cref="T:System.IO.Stream" /> and optionally releases the managed resources.
		/// </summary>
		/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
		protected override void Dispose(bool disposing)
		{
			ComDebug.ReportInfo("ComStreamWrapper.Dispose({0})", disposing);

			base.Dispose(disposing);

			Marshal.FreeCoTaskMem(_int64Ptr);
			_int64Ptr = IntPtr.Zero;

			Marshal.FreeCoTaskMem(_int32Ptr);
			_int32Ptr = IntPtr.Zero;

			if (null != _istream)
			{
				if (_isStreamOwner)
				{
					Marshal.ReleaseComObject(_istream);
					ComDebug.ReportInfo("ComStreamWrapper.Dispose: istream released");
				}
				_istream = null;
			}
		}
예제 #36
0
		public override void Close()
		{
			if (null != _istream)
			{
				//_istream.Commit(0);
				if (_isStreamOwner)
				{
					Marshal.ReleaseComObject(_istream);
					ComDebug.ReportInfo("ComStreamWrapper.Close: istream released");
				}
				_istream = null;
			}
			base.Close();
		}
예제 #37
0
 public virtual void UpdateModuleSymbols(ICorDebugAppDomain pAppDomain, ICorDebugModule pModule, IStream pSymbolStream) { pAppDomain.Continue(0); }
예제 #38
0
        public void Initialize(IStream pIStream, WICDecodeOptions cacheOptions)
        {
            Log.Trace("Initialize called");

            lock (this)
            {
                frame = null;
                stream = new WICReadOnlyStreamWrapper(pIStream);

                ReadExif();
            }
            Log.Trace("Initialize finished");
        }
예제 #39
0
        public void QueryCapability(IStream pIStream, out uint pdwCapability)
        {
            Log.Trace("QueryCapability called");
            var stream = new WICReadOnlyStreamWrapper(pIStream);
            var position = stream.Position;
            try
            {
                pdwCapability = (new PanasonicRW2Decoder().IsSupported(stream))
                    ? (uint)(WICBitmapDecoderCapabilities.WICBitmapDecoderCapabilityCanDecodeThumbnail
                    | WICBitmapDecoderCapabilities.WICBitmapDecoderCapabilityCanDecodeAllImages
                    | WICBitmapDecoderCapabilities.WICBitmapDecoderCapabilityCanEnumerateMetadata
                    | WICBitmapDecoderCapabilities.WICBitmapDecoderCapabilityCanDecodeThumbnail)
                    : 0;
            }
            catch (Exception)
            {
                pdwCapability = 0;
            }
            finally
            {
                stream.Position = position;

            }
        }
예제 #40
0
 internal void CloseElement()
 {
     Marshal.ReleaseComObject(m_iStream);
     m_iStream = null;
 }
예제 #41
0
		internal StreamWrapper(System.Runtime.InteropServices.ComTypes.IStream iStream)
        {
            m_iStream = iStream;
            Initialize();
        }