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);
     }
 }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
0
        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;
            }
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
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);
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
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);
        }
Exemplo n.º 9
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            ReportDebugStream("StreamWrapper.Read, bufferlength={0}, offset={1}, count={2}", buffer.Length, offset, count);
            int result = 0;

            if (0 == offset)
            {
                _istream.Read(buffer, count, _int32Ptr);
                result = Marshal.ReadInt32(_int32Ptr);
            }
            else
            {
                var len        = Math.Max(0, Math.Min(count, buffer.Length - offset));
                var tempBuffer = new byte[len];
                _istream.Read(tempBuffer, len, _int32Ptr);
                result = Marshal.ReadInt32(_int32Ptr);
                Buffer.BlockCopy(tempBuffer, 0, buffer, offset, result);
            }
            ReportDebugStreamBuffer("read", buffer, offset, result);
            return(result);
        }
Exemplo n.º 10
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);
            }
        }
Exemplo n.º 11
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();
            }
        }
Exemplo n.º 12
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"));
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Reads bytes from the stream
        /// </summary>
        /// <param name="buffer">buffer which will receive the bytes</param>
        /// <param name="offset">offset</param>
        /// <param name="count">number of bytes to be read</param>
        /// <returns>Returns the actual number of bytes read from the stream.</returns>
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (fileStream == null)
            {
                throw new ObjectDisposedException("fileStream", "storage stream no longer available");
            }
            int      i        = 0;
            object   local    = i;
            GCHandle gCHandle = new GCHandle();

            try
            {
                gCHandle = GCHandle.Alloc(local, GCHandleType.Pinned);
                IntPtr j = gCHandle.AddrOfPinnedObject();
                if (offset != 0)
                {
                    byte[] bs = new byte[count - 1];
                    fileStream.Read(bs, count, j);
                    i = (int)local;
                    Array.Copy(bs, 0, buffer, offset, i);
                }
                else
                {
                    fileStream.Read(buffer, count, j);
                    i = (int)local;
                }
            }
            finally
            {
                if (gCHandle.IsAllocated)
                {
                    gCHandle.Free();
                }
            }
            return(i);
        }
Exemplo n.º 14
0
        public void DownloadFile(PortableDeviceFile file, string saveToPath)
        {
            IPortableDeviceContent content;

            this._device.Content(out content);

            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;

            try
            {
                resources.GetStream(file.Id, ref property, 0, ref optimalTransferSize, out wpdStream);

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

                var        filename     = Path.GetFileName(file.Name);
                FileStream targetStream = new FileStream(Path.Combine(saveToPath, filename), FileMode.Create, FileAccess.Write);

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

                Marshal.ReleaseComObject(sourceStream);
                Marshal.ReleaseComObject(wpdStream);
            }
            catch
            {
                return;
            }
        }
Exemplo n.º 15
0
    public unsafe static void Create(string Path, object Stream, int BlockSize, int TotalBlocks)
    {
        int bytes = 0;

        byte[]               buf = new byte[BlockSize];
        System.IntPtr        ptr = (System.IntPtr)(&bytes);
        System.IO.FileStream o   = System.IO.File.OpenWrite(Path);
        System.Runtime.InteropServices.ComTypes.IStream i = Stream as System.Runtime.InteropServices.ComTypes.IStream;

        if (o == null)
        {
            return;
        }
        while (TotalBlocks-- > 0)
        {
            i.Read(buf, BlockSize, ptr);
            o.Write(buf, 0, bytes);
        }
        o.Flush();
        o.Close();
    }
        public void CopyFilefromDevice(PortableDeviceFile file, string saveToPath)
        {
            unsafe
            {
                IPortableDeviceContent       portableDeviceContent;
                IPortableDeviceResources     portableDeviceResource;
                PortableDeviceApiLib.IStream stream;
                int num = 0;

                _device.Content(out portableDeviceContent);
                portableDeviceContent.Transfer(out portableDeviceResource);

                uint num1 = 0;
                PortableDeviceApiLib._tagpropertykey __tagpropertykey = new PortableDeviceApiLib._tagpropertykey()
                {
                    fmtid = new Guid(-400655938, 13552, 16831, 181, 63, 241, 160, 106, 232, 120, 66),
                    pid   = 0
                };

                portableDeviceResource.GetStream(file.Id, ref __tagpropertykey, 0, ref num1, out stream);
                System.Runtime.InteropServices.ComTypes.IStream stream1 = (System.Runtime.InteropServices.ComTypes.IStream)stream;

                string str = (string.IsNullOrEmpty(file.Name) ? Path.GetFileName(file.Id) : Path.GetFileName(file.Name));

                var fileStream = new FileStream(Path.Combine(saveToPath, str), FileMode.Create, FileAccess.Write);

                byte[] numArray = new byte[1024];
                do
                {
                    //stream1.Read(numArray, 1024, new IntPtr(ref num));
                    stream1.Read(numArray, 1024, new IntPtr(&num));
                    fileStream.Write(numArray, 0, 1024);
                }while (num > 0);

                fileStream.Close();

                Marshal.ReleaseComObject(stream1);
                Marshal.ReleaseComObject(stream);
            }
        }
Exemplo n.º 17
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
                    {
                        int bytesRead = 9999;
                        for (; bytesRead > 0;)
                        {
                            bytesRead = 0;
                            sourceStream.Read(buffer, array_length, new IntPtr(&bytesRead));
                            targetStream.Write(buffer, 0, array_length);
                        }
                    }
                    finally
                    {
                        targetStream.Close();
                    }
                }
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                if (sourceStream != null)
                {
                    Marshal.ReleaseComObject(sourceStream);
                }
                if (wpdStream != null)
                {
                    Marshal.ReleaseComObject(wpdStream);
                }
            }
        }
Exemplo n.º 18
0
        private void TransferFile(string destination, bool overwrite)
        {
            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;
                FileMode mode;
                if (overwrite)
                {
                    mode = FileMode.Create;
                }
                else
                {
                    mode = FileMode.CreateNew;
                }
                FileStream targetStream = new FileStream(
                    destination,
                    mode,
                    FileAccess.Write);

                unsafe
                {
                    try
                    {
                        var buffer = new byte[1024];
                        int bytesRead;
                        do
                        {
                            sourceStream.Read(buffer, 1024, new IntPtr(&bytesRead));
                            targetStream.Write(buffer, 0, 1024);
                        } while (bytesRead > 0);
                    }
                    finally
                    {
                        targetStream.Close();
                    }
                }
            }
            catch (IOException)
            {
                throw new Exception("Destination file already exist!");
            }
            finally
            {
                Marshal.ReleaseComObject(sourceStream);
                Marshal.ReleaseComObject(wpdStream);
            }
        }
        unsafe public static object Load(System.Runtime.InteropServices.ComTypes.IStream stream)
        {
            // Exit if Stream is NULL
            if (stream == null)
            {
                return(null);
            }

            // Get Pointer to Int32
            int  cb;
            int *pcb = &cb;

            // Get Size of the object's Byte Array
            byte[] arrLen = new Byte[4];
            stream.Read(arrLen, arrLen.Length, new IntPtr(pcb));
            cb = BitConverter.ToInt32(arrLen, 0);

            // Read the object's Byte Array
            byte[] bytes = new byte[cb];
            stream.Read(bytes, cb, new IntPtr(pcb));

            if (bytes.Length != cb)
            {
                throw new Exception("Error reading object from stream");
            }

            // Deserialize byte array
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(PeristStreamHelper.ResolveEventHandler);
            object          data              = null;
            MemoryStream    memoryStream      = new MemoryStream(bytes);
            BinaryFormatter binaryFormatter   = new BinaryFormatter();
            object          objectDeserialize = binaryFormatter.Deserialize(memoryStream);

            if (objectDeserialize != null)
            {
                data = objectDeserialize;
            }
            memoryStream.Close();
            AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(PeristStreamHelper.ResolveEventHandler);

            //deserialize ArcObjects
            if (data is string)
            {
                string str = (string)data;
                if (str.IndexOf("http://www.esri.com/schemas/ArcGIS/9.2") != -1)
                {
                    IXMLStream readerStream = new XMLStreamClass();
                    readerStream.LoadFromString(str);

                    IXMLReader xmlReader = new XMLReaderClass();
                    xmlReader.ReadFrom((IStream)readerStream);

                    IXMLSerializer xmlReadSerializer = new XMLSerializerClass();
                    object         retObj            = xmlReadSerializer.ReadObject(xmlReader, null, null);
                    if (null != retObj)
                    {
                        data = retObj;
                    }
                }
            }

            return(data);
        }
Exemplo n.º 20
0
        /**
         * Copy To PC
         */
        public void TransferContentFromDevice(PortableDeviceFile file, string saveToPath, String fileName)
        {
            FileStream targetStream = null;

            try
            {
                // make sure that we are not holding on to a file.
                DisconnectConnect();

                // Make sure that the target dir exists.
                System.IO.Directory.CreateDirectory(saveToPath);

                IPortableDeviceContent content = getContents();

                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.Id, ref property, 0, ref optimalTransferSize, out wpdStream);

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

                // var fileName = Path.GetFileName(file.Id);
                targetStream = new FileStream(Path.Combine(saveToPath, fileName), FileMode.Create, FileAccess.Write);

                // Getthe total size.
                long length  = file.size;
                long written = 0;
                long lPCt    = 0;
                unsafe
                {
                    var buffer = new byte[1024];
                    int bytesRead;
                    do
                    {
                        sourceStream.Read(buffer, 1024, new IntPtr(&bytesRead));
                        targetStream.Write(buffer, 0, bytesRead);

                        written += 1024;
                        long PCt = length > 0 ? (100 * written) / length : 100;
                        if (PCt != lPCt)
                        {
                            lPCt = PCt;
                            Console.WriteLine("Progress: " + lPCt);
                        }
                    } while (bytesRead > 0);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw ex;
            }
            finally
            {
                if (null != targetStream)
                {
                    targetStream.Close();
                }
                Disconnect();
            }
        }
Exemplo n.º 21
0
        private bool TransferContentFromDevice(string toFile, string objectId, bool isReadNew = false)
        {
            bool       bRet    = true;
            string     oldFile = Path.GetDirectoryName(toFile) + "\\" + Path.GetFileNameWithoutExtension(toFile) + "_old" + Path.GetExtension(toFile);
            FileStream fsOld   = null;

            byte[] bufferOld    = null;
            int    bytesReadOld = 0;
            bool   isFileNew    = false;

            string folder = Path.GetDirectoryName(toFile);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            if (isReadNew)
            {
                if (File.Exists(oldFile))
                {
                    File.Delete(oldFile);
                }

                if (File.Exists(toFile))
                {
                    File.Move(toFile, oldFile);
                }
                else
                {
                    File.Create(oldFile);
                }

                fsOld     = new FileStream(oldFile, FileMode.Open, FileAccess.Read);
                bufferOld = new byte[512 * 1024];
            }

            if (File.Exists(toFile))
            {
                File.Delete(toFile);
            }



            IPortableDeviceResources resources;

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

            try
            {
                //设备建议读取长度optimalTransferSize长度一般为262144即256k,
                resources.GetStream(objectId, ref pKey.WPD_RESOURCE_DEFAULT, 0, ref optimalTransferSize, out wpdStream);
                System.Runtime.InteropServices.ComTypes.IStream sourceStream = (System.Runtime.InteropServices.ComTypes.IStream)wpdStream;

                string     filename     = Path.GetFileName(toFile);
                FileStream targetStream = new FileStream(toFile, FileMode.Create, FileAccess.Write);
                {
                    int    filesize        = (int)optimalTransferSize;
                    byte[] buffer          = new byte[filesize];
                    int    bytesRead       = 0;
                    IntPtr bytesReadIntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(bytesRead));

                    do
                    {
                        sourceStream.Read(buffer, filesize, bytesReadIntPtr);
                        bytesRead = Marshal.ReadInt32(bytesReadIntPtr);
                        if (filesize > bytesRead)
                        {
                            filesize = bytesRead;
                        }

                        if (isReadNew && isFileNew == false)
                        {
                            bytesReadOld = fsOld.Read(bufferOld, 0, bytesRead);
                            if (bytesReadOld != bytesRead ||
                                IsDataDiff(buffer, bufferOld, bytesRead))
                            {
                                isFileNew = true;
                            }
                        }

                        targetStream.Write(buffer, 0, filesize);
                    } while (bytesRead > 0);

                    targetStream.Close();
                    targetStream.Dispose();


                    Marshal.FreeCoTaskMem(bytesReadIntPtr);
                }
            }
            catch (Exception)
            {
                bRet = false;
            }
            finally
            {
                //若不添此行,在本方法执行一次后再次执行时会报资源占用错误
                Marshal.ReleaseComObject(wpdStream);

                if (isReadNew)
                {
                    fsOld.Close();
                    File.Delete(oldFile);
                    bRet = (isFileNew == false && bRet == false ? false : true);
                }
            }

            return(bRet);
        }
Exemplo n.º 22
0
        public bool DownloadFile(PortableDeviceFile file, string saveToPath)
        {
            bool isdownload = false;
            IPortableDeviceContent content;

            this._device.Content(out content);

            IPortableDeviceResources resources;

            content.Transfer(out resources);

            PortableDeviceApiLib.IStream wpdStream;
            uint optimalTransferSize = 0;

            System.Runtime.InteropServices.ComTypes.IStream sourceStream = null;

            IPortableDeviceValues values =
                new PortableDeviceTypesLib.PortableDeviceValues() as IPortableDeviceValues;

            DateTime  createdDate = GetObjectCreationTime(content, file.Id);
            ImageItem imageItem   = null;

            imageItem = new ImageItem(0, file.Id, file.Name, createdDate);


            var property = new _tagpropertykey();

            property.fmtid = new Guid(0xE81E79BE, 0x34F0, 0x41BF, 0xB5, 0x3F, 0xF1, 0xA0, 0x6A, 0xE8, 0x78, 0x42);
            property.pid   = 0;
            string     imgpath      = string.Empty;
            FileStream targetStream = null;

            try
            {
                resources.GetStream(file.Id, ref property, 0, ref optimalTransferSize, out wpdStream);

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

                var filename = Path.GetFileName(file.Id);
                imgpath      = saveToPath + "IMG_1_" + imageItem.TakenTime.ToString() + "_" + file.Id + ".jpg";
                targetStream = new FileStream(imgpath, FileMode.Create, FileAccess.Write);

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


                    isdownload = true;
                }
            }
            catch (Exception ex)
            {
                isdownload = false;
                Logger.Basic.Error("PortableDevice DownloadFile : " + ex.ToString(), ex);
            }
            finally
            {
                if (resources != null && Marshal.IsComObject(resources))
                {
                    Marshal.ReleaseComObject(resources);
                }

                if (content != null && Marshal.IsComObject(content))
                {
                    Marshal.ReleaseComObject(content);
                }

                if (sourceStream != null && Marshal.IsComObject(sourceStream))
                {
                    Marshal.ReleaseComObject(sourceStream);
                }

                if (!isdownload)
                {
                    if (File.Exists(imgpath))
                    {
                        if (targetStream != null)
                        {
                            targetStream.Close();
                        }

                        File.Delete(imgpath);
                    }
                }
            }

            return(isdownload);
        }
Exemplo n.º 23
0
        // COPY inside of the same WPD
        public bool CopyInsideWPD2(PortableDeviceFile file, string parentObjectId)
        {
            bool success = false;

            // WPD source
            IPortableDeviceContent contentSrc;

            this._device.Content(out contentSrc);
            IPortableDeviceResources resourcesSrc;

            contentSrc.Transfer(out resourcesSrc);
            PortableDeviceApiLib.IStream wpdStreamSrc;
            uint            optimalTransferSizeSrc = 0;
            _tagpropertykey propertySrc            = new _tagpropertykey();

            propertySrc.fmtid = new Guid(0xE81E79BE, 0x34F0, 0x41BF, 0xB5, 0x3F, 0xF1, 0xA0, 0x6A, 0xE8, 0x78, 0x42);
            propertySrc.pid   = 0;
            resourcesSrc.GetStream(file.Id, ref propertySrc, 0, ref optimalTransferSizeSrc, out wpdStreamSrc);
            System.Runtime.InteropServices.ComTypes.IStream streamSrc = (System.Runtime.InteropServices.ComTypes.IStream)wpdStreamSrc;

            // WPD destination
            IPortableDeviceContent contentDst;

            this._device.Content(out contentDst);
            IPortableDeviceValues values = this.GetRequiredPropertiesForCopyWPD(file, parentObjectId);

            PortableDeviceApiLib.IStream tempStream;
            uint optimalTransferSizeBytes = 0;

            contentDst.CreateObjectWithPropertiesAndData(values, out tempStream, ref optimalTransferSizeBytes, null);
            System.Runtime.InteropServices.ComTypes.IStream streamDst = (System.Runtime.InteropServices.ComTypes.IStream)tempStream;

            try {
                unsafe {
                    byte[] buffer = new byte[1024];
                    int    bytesRead;
                    do
                    {
                        // read from source
                        streamSrc.Read(buffer, 1024, new IntPtr(&bytesRead));

                        // write to destination
                        IntPtr pcbWritten = IntPtr.Zero;
                        if (bytesRead > 0)
                        {
                            streamDst.Write(buffer, bytesRead, pcbWritten);
                        }
                    } while (bytesRead > 0);
                }
                success = true;
                streamDst.Commit(0);
            } catch (Exception) {
                success = false;
            } finally {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(tempStream);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(streamSrc);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wpdStreamSrc);
            }

            return(success);
        }