static int Main()
    {
        byte [] buf = new byte [1];
        AsyncCallback ac = new AsyncCallback (async_callback);
        IAsyncResult ar;
        int sum0 = 0;

        FileStream s = new FileStream ("async_read.cs",  FileMode.Open);

        s.Position = 0;
        sum0 = 0;
        while (s.Read (buf, 0, 1) == 1)
            sum0 += buf [0];

        s.Position = 0;

        do {
            ar = s.BeginRead (buf, 0, 1, ac, buf);
        } while (s.EndRead (ar) == 1);
        sum -= buf [0];

        Thread.Sleep (100);

        s.Close ();

        Console.WriteLine ("CSUM: " + sum + " " + sum0);
        if (sum != sum0)
            return 1;

        return 0;
    }
Пример #2
1
	public static bool SendFileToPrinter( string szPrinterName, string szFileName )
	{
		// Open the file.
		FileStream fs = new FileStream(szFileName, FileMode.Open);
		// Create a BinaryReader on the file.
		BinaryReader br = new BinaryReader(fs);
		// Dim an array of bytes big enough to hold the file's contents.
		Byte []bytes = new Byte[fs.Length];
		bool bSuccess = false;
		// Your unmanaged pointer.
		IntPtr pUnmanagedBytes = new IntPtr(0);
		int nLength;

		nLength = Convert.ToInt32(fs.Length);
		// Read the contents of the file into the array.
		bytes = br.ReadBytes( nLength );
		// Allocate some unmanaged memory for those bytes.
		pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
		// Copy the managed byte array into the unmanaged array.
		Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
		// Send the unmanaged bytes to the printer.
		bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
		// Free the unmanaged memory that you allocated earlier.
		Marshal.FreeCoTaskMem(pUnmanagedBytes);
		return bSuccess;
	}
Пример #3
1
        public void AppendResultsToFile(String Name, double TotalTime)
        {
            FileStream file;
            file = new FileStream(Name, FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(file);

            sw.Write("***************************************\n");

            sw.Write("Total  | No Subs| %Total |%No Subs| Name\n");

            foreach (CNamedTimer NamedTimer in m_NamedTimerArray)
            {
                if (NamedTimer.GetTotalSeconds() > 0)
                {
                    String OutString;

                    OutString = String.Format("{0:0.0000}", NamedTimer.GetTotalSeconds())
                        + " | " + String.Format("{0:0.0000}", NamedTimer.GetTotalSecondsExcludingSubroutines())
                        + " | " + String.Format("{0:00.00}", System.Math.Min(99.99, NamedTimer.GetTotalSeconds() / TotalTime * 100)) + "%"
                        + " | " + String.Format("{0:00.00}", NamedTimer.GetTotalSecondsExcludingSubroutines() / TotalTime * 100) + "%"
                        + " | "
                        + NamedTimer.m_Name;

                    OutString += " (" + NamedTimer.m_Counter.ToString() + ")\n";
                    sw.Write(OutString);
                }
            }

            sw.Write("\n\n");

            sw.Close();
            file.Close();
        }
Пример #4
0
        private static SafeMemoryMappedFileHandle CreateCore(
            FileStream fileStream, string mapName, HandleInheritability inheritability,
            MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity)
        {
            SafeFileHandle fileHandle = fileStream != null ? fileStream.SafeFileHandle : null;
            Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability);


            SafeMemoryMappedFileHandle handle = fileHandle != null ?
                Interop.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName) :
                Interop.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName);

            int errorCode = Marshal.GetLastWin32Error();
            if (!handle.IsInvalid)
            {
                if (errorCode == Interop.Errors.ERROR_ALREADY_EXISTS)
                {
                    handle.Dispose();
                    throw Win32Marshal.GetExceptionForWin32Error(errorCode);
                }
            }
            else // handle.IsInvalid
            {
                handle.Dispose();
                throw Win32Marshal.GetExceptionForWin32Error(errorCode);
            }

            return handle;
        }
Пример #5
0
    private static void Assemble(List<string> files, string destinationDirectory)
    {
        string fileOutputPath = destinationDirectory + "assembled" + "." + matches[0].Groups[2];
        var fsSource = new FileStream(fileOutputPath, FileMode.Create);

        fsSource.Close();
        using (fsSource = new FileStream(fileOutputPath, FileMode.Append))
        {
            foreach (var filePart in files)
            {
                using (var partSource = new FileStream(filePart, FileMode.Open))
                {
                    Byte[] bytePart = new byte[4096];
                    while (true)
                    {
                        int readBytes = partSource.Read(bytePart, 0, bytePart.Length);
                        if (readBytes == 0)
                        {
                            break;
                        }

                        fsSource.Write(bytePart, 0, readBytes);
                    }
                }
            }
        }
    }
 private static void Assemble(List<string> files, string destinationDirectory)
 {
     var allData = new List<byte>();
         for (int i = 0; i < files.Count; i++)
         {
             var sourceFile = files[i];
             using (var source = new FileStream(sourceFile, FileMode.Open))
             {
                 using (var zip = new GZipStream(source, CompressionMode.Decompress))
                 {
                     byte[] buffer = new byte[4096];
                     while (true)
                     {
                         int readBytes = zip.Read(buffer, 0, buffer.Length);
                         if (readBytes == 0)
                         {
                             break;
                         }
                         for (int j = 0; j < readBytes; j++)
                         {
                             allData.Add(buffer[j]);
                         }
                     }
                 }
             }
         }
         using (var copy = new FileStream(destinationDirectory, FileMode.Create))
         {
             copy.Write(allData.ToArray(), 0, allData.Count);
         }
 }
Пример #7
0
        public void UploadFile(RemoteFileInfo request)
        {
            try
            {
                FileGonnaGo objFileUpload = new FileGonnaGo();
                if (objFileUpload.impersonateValidUser())
                {
                    FileStream targetStream = null;
                    Stream sourceStream = request.FileByteStream;
                    string uploadFolder = objFileServerImpersonation.FileServerPath();
                    string filePath = Path.Combine(uploadFolder, request.FileName);

                    using (targetStream = new FileStream(filePath, FileMode.Create,
                                      FileAccess.Write, FileShare.None))
                    {

                        const int bufferLen = 21474833;
                        byte[] buffer = new byte[bufferLen];
                        int count = 0;
                        while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                        {
                            targetStream.Write(buffer, 0, count);
                        }
                        targetStream.Close();
                        sourceStream.Close();
                    }
                    objFileUpload.undoImpersonation();
                }
            }
            catch (Exception ex)
            {
                WCFFILESERVER.FileService.LogException(string.Empty, ex);
                throw;
            }
        }
Пример #8
0
	/// <summary>
	/// Writes the input stream to the target file.
	/// </summary>
	/// <param name="source" this="true">The source stream to write to the target file.</param>
	/// <param name="targetFile">The target file to write to.</param>
	/// <param name="append">If set to <see langword="true"/> and the file exists, then appends the source stream, otherwise, it will overwrite it.</param>
	public static void WriteTo(this Stream source, string targetFile, bool append = false)
	{
		using (var output = new FileStream(targetFile, append ? FileMode.Append : FileMode.Create))
		{
			source.WriteTo(output);
		}
	}
	/**
     * open file.
     * @param void.
     * @return void.
     */
	public bool Open(string strFileName, FileMode eMode, FileAccess eAccess)
	{
		if (string.IsNullOrEmpty(strFileName))
		{
			return false;
		}
		
		if ((FileMode.Open == eMode) && !File.Exists(strFileName))
		{
			return false;
		}
		
		try
		{
			m_cStream = new FileStream(strFileName, eMode, eAccess);
		}
		catch (Exception cEx)
		{
			Console.Write(cEx.Message);
		}
		
		if (null == m_cStream)
		{
			return false;
		}
		
		m_bOpen = true;
		return true;
	}
Пример #10
0
	void Serialize(string filename){
		// normalizes the data to the {0.0-1.0f} interval and saves as xml
		Waveform w = new Waveform();
		w.name = filename;
		w.cycles=1;
		w.signal = signal;
		w.mode=filename;
		w.normalRate = normal;
		w.samples = dataPoints.Count;
		
		float scale = dataMax-dataMin;
		if ( scale == 0.0f )
			scale = 1.0f;
		
		w.data = new float[dataPoints.Count];
		
		for (int i=0;i< dataPoints.Count;i++){
			w.data[i]= (dataPoints[i].point-dataMin)/scale;
			
		}
		XmlSerializer serializer = new XmlSerializer(typeof(Waveform));
		FileStream stream = new FileStream(filename + ".xml", FileMode.Create);
		serializer.Serialize(stream, w);
		stream.Close();	
	}	
Пример #11
0
    /// <summary>
    /// Loads the SessionDetails object from serialized xml SessionDetails file.
    /// </summary>
    /// <param name="serializeFileName">file Path of xml serialized SessionDetails object.</param>
    /// <returns>SessionDetails object.</returns>
    public static SessionDetails Load(string serializeFileName)
    {
        SessionDetails RetVal = null;
        FileStream _IO = null;
        if (File.Exists(serializeFileName))
        {
            try
            {
                _IO = new FileStream(serializeFileName, FileMode.Open);
                XmlSerializer _SRZFrmt = new XmlSerializer(typeof(SessionDetails));
                RetVal = (SessionDetails)_SRZFrmt.Deserialize(_IO);

            }
            catch (System.Runtime.Serialization.SerializationException ex)
            {
                Global.CreateExceptionString(ex, null);
                //throw;
            }
            finally
            {
                if (_IO != null)
                {
                    _IO.Flush();
                    _IO.Close();
                }
            }
        }

        return RetVal;
    }
 public Stream GetPicture()
 {
     string fileName = Path.Combine(HostingEnvironment.ApplicationPhysicalPath,"vista.jpg");
     FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
     System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
     return (Stream)fileStream;
 }
Пример #13
0
        public static void Write(FileStream aThis, byte[] aBuffer, int aOffset, int aCount,
            [FieldAccess(Name = "$$InnerStream$$")] ref Stream innerStream)
        {
            Global.mFileSystemDebugger.SendInternal("FileStream.Write:");

            innerStream.Write(aBuffer, aOffset, aCount);
        }
Пример #14
0
        public static int Read(FileStream aThis, byte[] aBuffer, int aOffset, int aCount,
            [FieldAccess(Name = "$$InnerStream$$")] ref Stream innerStream)
        {
            Global.mFileSystemDebugger.SendInternal("FileStream.Read:");

            return innerStream.Read(aBuffer, aOffset, aCount);
        }
Пример #15
0
        // This plug basically forwards all calls to the $$InnerStream$$ stream, which is supplied by the file system.

        //  public static unsafe void Ctor(String aThis, [FieldAccess(Name = "$$Storage$$")]ref Char[] aStorage, Char[] aChars, int aStartIndex, int aLength,

        public static void Ctor(FileStream aThis, string aPathname, FileMode aMode,
            [FieldAccess(Name = "$$InnerStream$$")] ref Stream innerStream)
        {
            Global.mFileSystemDebugger.SendInternal("FileStream.Ctor:");

            innerStream = InitializeStream(aPathname, aMode);
        }
Пример #16
0
    static IEnumerator Compute(string path, OnFinish on_finish)
    {
        FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
        byte[] buffer = new byte[kBlockSize];
        MD5 md5 = MD5.Create();
        int length, read_bytes;

        while (stream.Position < stream.Length)
        {
            length = (stream.Position + kBlockSize > stream.Length) ? (int)(stream.Length - stream.Position) : kBlockSize;
            read_bytes = stream.Read(buffer, 0, length);

            if (stream.Position < stream.Length)
            {
                md5.TransformBlock(buffer, 0, read_bytes, buffer, 0);
            }
            else
            {
                md5.TransformFinalBlock(buffer, 0, read_bytes);
                stream.Close();
                break;
            }

            yield return new WaitForEndOfFrame();
        }

        string md5hash = "";
        foreach (byte n in md5.Hash)
            md5hash += n.ToString("x2");

        Fun.DebugUtils.Log(String.Format("MD5 >> {0} > {1}", stream.Name, md5hash));

        if (on_finish != null)
            on_finish(md5hash);
    }
Пример #17
0
    private static void Assemble(List<string> files, string destinationDirectory)
    {
        // creating the file path for the reconstructed file
        string fileOutputPath = destinationDirectory + "assembled" + "." + matches[0].Groups[2];
        var fsSource = new FileStream(fileOutputPath, FileMode.Create);

        fsSource.Close();
        using (fsSource = new FileStream(fileOutputPath, FileMode.Append))
        {
            // reading the file paths of the parts from the files list
            foreach (var filePart in files)
            {
                using (var partSource = new FileStream(filePart, FileMode.Open))
                {
                    // Create a byte array of the content of the current file
                    Byte[] bytePart = new byte[4096];
                    while (true)
                    {
                        int readBytes = partSource.Read(bytePart, 0, bytePart.Length);
                        if (readBytes == 0)
                        {
                            break;
                        }

                        // Write the bytes to the reconstructed file
                        fsSource.Write(bytePart, 0, readBytes);
                    }
                }
            }
        }
    }
Пример #18
0
 static void Slice(string destinationDirectory, int parts)
 {
     using (var sourceFile = new FileStream(destinationDirectory, FileMode.Open))
     {
     long partLength = sourceFile.Length / parts;
     long lastPartLength = (sourceFile.Length % parts) + (sourceFile.Length / parts);
     for (int i = 0; i < parts; i++)
     {
         using (var destination = new FileStream("../../Part " + (i + 1).ToString() + ".txt", FileMode.Create))
         {
             byte[] buffer;
             if (i == parts - 1)
             {
                 buffer = new byte[lastPartLength];
             }
             else
             {
                 buffer = new byte[partLength];
             }
             sourceFile.Read(buffer, 0, buffer.Length);
             destination.Write(buffer, 0, buffer.Length);
         }
     }
     }
 }
Пример #19
0
	public static string LoadName(string path)
	{
		// The idea is to read only the number of bytes we need to determine the name of the timeline
		// We're going to exploit our knowledge of the way the unpacker works to do this - kinda hacky, but eh
		// Maybe one of these days I'll change the unpacker over to work with streams instead of byte arrays
		// Probably not
		// ...definitely not
		FileStream fs = new FileStream(path, FileMode.Open);

		// Skip over the version
		fs.Position = 4;	

		// Read the length of the string
		byte[] strLengthBytes = new byte[4];
		fs.Read(strLengthBytes, 0, 4);
		int strLength = BitConverter.ToInt32(strLengthBytes, 0);

		// Read the actual string data
		byte[] strBytes = new byte[strLength];
		fs.Read(strBytes, 0, strLength);

		// Tidy up the stream
		fs.Close();

		// Unpack and return the string
        char[] cArray = System.Text.Encoding.Unicode.GetChars(strBytes, 0, strBytes.Length);
        return new string(cArray);
	}
Пример #20
0
 public static void SaveToFile(Level data, string fileName)
 {
     IFormatter formatter = new BinaryFormatter();
     Stream stream = new FileStream(string.Format("{0}.level", fileName), FileMode.Create, FileAccess.Write, FileShare.Write);
     formatter.Serialize(stream, data);
     stream.Close();
 }
Пример #21
0
    public void Write(string logfilename, string log, LogType lt)
    {
#if UNITY_IPHONE || UNITY_ANDROID
        return;
#endif
        string filePathName = WriteFile(logfilename);

        FileStream fs = new FileStream(filePathName, FileMode.Append);
        StreamWriter sw = new StreamWriter(fs);
        //开始写入 
        sw.WriteLine("");
        //
        string str = "[";
        str += System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");//默认当天时间。
        str += "]";
        str += "\t";
        str += lt.ToString();
        str += "\t";
        str += log;

        sw.Write(str);
        //清空缓冲区 
        sw.Flush();
        //关闭流 
        sw.Close();
        fs.Close();
    }
Пример #22
0
    public static bool Load(Chunk chunk)
    {

        string saveFile = SaveLocation(chunk.world.worldName);
        saveFile += FileName(chunk.pos);

        if (!File.Exists(saveFile))
            return false;
        try
        {

            IFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(saveFile, FileMode.Open);

            Save save = (Save)formatter.Deserialize(stream);

            //Once the blocks in the save are added they're marked as unmodified so
            //as not to trigger a new save on unload unless new blocks are added.
            for (int i =0; i< save.blocks.Length; i++)
            {
                Block placeBlock = save.blocks[i];
                placeBlock.modified = false;
                chunk.SetBlock(save.positions[i], placeBlock, false);
            }

            stream.Close();
        }
        catch (Exception ex)
        {
            Debug.LogError(ex);
        }


        return true;
    }
Пример #23
0
    //------------------------------------------------------------------------------------------------------------
    private void OnGUI()
    {
        m_MeshFilter = (MeshFilter)EditorGUILayout.ObjectField("MeshFilter", m_MeshFilter, typeof(MeshFilter), true);
		
		if (m_MeshFilter != null)
		{
			if (GUILayout.Button("Export OBJ"))
			{
				var lOutputPath = EditorUtility.SaveFilePanel("Save Mesh as OBJ", "", m_MeshFilter.name + ".obj", "obj");
				
				if (File.Exists(lOutputPath))
				{
					File.Delete(lOutputPath);
				}
				
				var lStream = new FileStream(lOutputPath, FileMode.Create);
				var lOBJData = m_MeshFilter.sharedMesh.EncodeOBJ();
				OBJLoader.ExportOBJ(lOBJData, lStream);
				lStream.Close();
			}
		}
		else
		{
			GUILayout.Label("Please provide a MeshFilter");
		}
    }
Пример #24
0
	private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
	 {
        FileStream fs = new FileStream(inName, FileMode.Open, FileAccess.Read);
        // Create an instance of the Rijndael cipher
        SymmetricAlgorithm aes = Rijndael.Create();
        // set the key to be the derivedKey computed above
        aes.Key = desKey;
        // set the IV to be all zeros
        aes.IV = desIV;  // arrays are zero-initialized
        // now wrap an encryption transform around the filestream
        CryptoStream stream1 = new CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Read);
        // The result of reading from stream1 is ciphertext, but we want it
        // base64-encoded, so wrap another transform around it
        CryptoStream stream2 = new CryptoStream(stream1, new ToBase64Transform(), CryptoStreamMode.Read);

        FileStream fsout = new FileStream(outName, FileMode.OpenOrCreate);
        byte[] buffer = new byte[1024];
        int bytesRead;
        do {
            bytesRead = stream2.Read(buffer,0,1024);
            fsout.Write(buffer,0,bytesRead);
        } while (bytesRead > 0);
        fsout.Flush();
        fsout.Close();
    }
Пример #25
0
        public async Task AnonymousPipeWriteViaFileStream(bool asyncWrites)
        {
            using (var server = new AnonymousPipeServerStream(PipeDirection.In))
            {
                Task serverTask = Task.Run(() =>
                {
                    for (int i = 0; i < 6; i++)
                        Assert.Equal(i, server.ReadByte());
                });

                using (var client = new FileStream(new SafeFileHandle(server.ClientSafePipeHandle.DangerousGetHandle(), false), FileAccess.Write, bufferSize: 3))
                {
                    var data = new[] { new byte[] { 0, 1 }, new byte[] { 2, 3 }, new byte[] { 4, 5 } };
                    foreach (byte[] arr in data)
                    {
                        if (asyncWrites)
                            await client.WriteAsync(arr, 0, arr.Length);
                        else
                            client.Write(arr, 0, arr.Length);
                    }
                }

                await serverTask;
            }
        }
Пример #26
0
    private void Init() {

        if (!File.Exists(file)){
            myFs = new FileStream(file, FileMode.Create);
        }
        mySw = new StreamWriter(file, true, System.Text.Encoding.GetEncoding("utf-8"));
    }    
Пример #27
0
	private void Read(string filename)
	{
		XmlSerializer ser=new XmlSerializer(typeof(DataSet));
		FileStream fs=new FileStream(filename, FileMode.Open);
		DataSet ds;

		ds=(DataSet)ser.Deserialize(fs);
		fs.Close();
		
		Console.WriteLine("DataSet name: "+ds.DataSetName);
		Console.WriteLine("DataSet locale: "+ds.Locale.Name);

		foreach(DataTable t in ds.Tables) 
		{
			Console.WriteLine("Table name: "+t.TableName);
			Console.WriteLine("Table locale: "+t.Locale.Name);

			foreach(DataColumn c in t.Columns) 
			{
				Console.WriteLine("Column name: "+c.ColumnName);
				Console.WriteLine("Null allowed? "+c.AllowDBNull);
				
			}

			foreach(DataRow r in t.Rows)
			{
				Console.WriteLine("Row: "+(string)r[0]);
			}
		}
	}
Пример #28
0
    static void Assemble(List<string> files, string destinationDirectory)
    {
        string fileOutputPath = destinationDirectory + "assembled" + "." + matches[0].Groups[3];
        var fsSource = new FileStream(fileOutputPath, FileMode.Create);
        fsSource.Close();

        using (fsSource = new FileStream(fileOutputPath, FileMode.Append))
        {
            // reading the file paths of the parts from the files list
            foreach (var filePart in files)
            {
                using (var partSource = new FileStream(filePart, FileMode.Open))
                {
                    using (var compressionStream = new GZipStream(partSource,CompressionMode.Decompress,false))
                    {
                        // copy the bytes from part to new assembled file
                        Byte[] bytePart = new byte[4096];
                        while (true)
                        {
                            int readBytes = compressionStream.Read(bytePart, 0, bytePart.Length);
                            if (readBytes == 0)
                            {
                                break;
                            }

                            fsSource.Write(bytePart, 0, readBytes);
                        }
                    }
                }
            }
        }
    }
Пример #29
0
    public void ImportProteinSettings()
    {
        try
        {
            ////read
            serializer = new XmlSerializer(typeof(CutParametersContainer));
            stream = new FileStream(path, FileMode.Open);
            CutParametersContainer importParams = serializer.Deserialize(stream) as CutParametersContainer;
            stream.Close();

            for (int i = 0; i < importParams.CutObjectProps.Count && i < SceneManager.Get.CutObjects.Count; i++)
            {
                SceneManager.Get.CutObjects[i].IngredientCutParameters = importParams.CutObjectProps[i].ProteinTypeParameters;
                SceneManager.Get.CutObjects[i].Inverse = importParams.CutObjectProps[i].Inverse;
                SceneManager.Get.CutObjects[i].CutType = (CutType) importParams.CutObjectProps[i].CutType;

                //restore transform info
                SceneManager.Get.CutObjects[i].transform.rotation = importParams.CutObjectProps[i].rotation;
                SceneManager.Get.CutObjects[i].transform.position = importParams.CutObjectProps[i].position;
                SceneManager.Get.CutObjects[i].transform.localScale = importParams.CutObjectProps[i].scale;
            }
        }
        catch(Exception e)
        {
            Debug.Log("import failed: " + e.ToString());
            return;
        }

        Debug.Log("imported cutobject settings from " + path);
    }
Пример #30
0
    public void ExportProteinSettings()
    {
        try
        {
            CutParametersContainer exportParams = new CutParametersContainer();

            foreach (CutObject cuto in SceneManager.Get.CutObjects)
            {
                CutObjectProperties props = new CutObjectProperties();
                props.ProteinTypeParameters = cuto.IngredientCutParameters;
                props.Inverse = cuto.Inverse;
                props.CutType = (int)cuto.CutType;
                props.rotation = cuto.transform.rotation;
                props.position = cuto.transform.position;
                props.scale = cuto.transform.localScale;
                exportParams.CutObjectProps.Add(props);            
            }

            ////write
            serializer = new XmlSerializer(typeof(CutParametersContainer));
            stream = new FileStream(path, FileMode.Create);
            serializer.Serialize(stream, exportParams);
            stream.Close();
        }
        catch(Exception e)
        {
            Debug.Log("export failed: " + e.ToString());
            return;
        }

        Debug.Log("exported cutobject settings to " + path);
    }
        public async Task Invoke(HttpContext httpContext, IHostingEnvironment hostingEnvironment)
        {
            if (httpContext.WebSockets.IsWebSocketRequest)
            {
                //升级协议,建立链接。返回代表此链接的websocket对象。
                socket = await httpContext.WebSockets.AcceptWebSocketAsync();
                var buffer = new byte[options.ReceiveBufferSize];
                List<byte> msgArr = new List<byte>();
                //开始侦听socket,获取消息。此时可以向客户端发送消息。
                //接收到消息后,消息将传入到buffer中。
                //WebSocketResult 消息接收结果。
                //result.CloseStatus 关闭状态
                //result.CloseStatusDescription 关闭状态描述
                //result.Count 接收的消息长度
                //result.EndOfMessage 是否已经接受完毕
                //result.MessageType 消息类型 Text(文字,默认UTF-8编码),Binary(二进制),Close(关闭消息);
                var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                //当关闭状态没有值时:
                while(!result.CloseStatus.HasValue)
                {
                    msgArr.Clear();
                    //循环接收消息。
                    while (!result.EndOfMessage)
                    {
                        msgArr.AddRange(new ArraySegment<byte>(buffer, 0, result.Count));
                        result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                    }
                    msgArr.AddRange(new ArraySegment<byte>(buffer, 0, result.Count));
                    switch (result.MessageType)
                    {
                        case System.Net.WebSockets.WebSocketMessageType.Binary:
                            try
                            {
                                var fileName = Path.Combine(hostingEnvironment.WebRootPath, Guid.NewGuid().ToString() + ".png");
                                using (FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate))
                                {
                                    await fileStream.WriteAsync(msgArr.ToArray(), 0, msgArr.Count());
                                }
                            }
                            catch(FileNotFoundException fileNotFound)
                            {
                                await socket.SendAsync(new ArraySegment<byte>(socketEncoding.Encode(fileNotFound.Message)), System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);
                            }
                            catch(InvalidOperationException inEx)
                            {
                                await socket.SendAsync(new ArraySegment<byte>(socketEncoding.Encode(inEx.Message)), System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);
                            }
                            catch(Exception e)
                            {
                                await socket.SendAsync(new ArraySegment<byte>(socketEncoding.Encode(e.Message)), System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);
                            }
                            break;
                        case System.Net.WebSockets.WebSocketMessageType.Close:
                            //关闭链接。
                            await socket.CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, "客户端关闭", CancellationToken.None);
                            break;
                        case System.Net.WebSockets.WebSocketMessageType.Text:
                            //获取客户端发送的消息。消息编码,采用UTF8
                            var message = socketEncoding.Decode(msgArr.ToArray());
                            //回显数据
                            await SendMessage("OK \t" + message);
                            break;
                        default:
                            break;
                    }
                    result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer),CancellationToken.None);
                }

            }
            else
            {
                await _next(httpContext);
            }
        }
Пример #32
0
        /// <summary>
        /// 解析导联表
        /// </summary>
        /// <param name="fs">文件流</param>
        /// <param name="encoding">编码</param>
        /// <summary>
        /// 解析导联列表
        /// </summary>
        private void parseSignals(FileStream fs, Encoding encoding)
        {
            // 读取导联列表
            var buffer = new byte[this._header.NumberOfSignalsInDataRecord * SIGNAL_LENGTH];

            //Debug.WriteLine("NumberOfSignalsInDataRecord长度" + this._header.NumberOfSignalsInDataRecord);

            /*
             * 新建字节数组 buffer  长度为信号数据记录数*信号长度(256)
             */

            fs.Read(buffer, 0, buffer.Length); //从文件里读出数据
                                               //string debugStr = $"导联表数据({buffer.Length}):\n";
                                               //for (var i = 0; i < buffer.Length; i++)
                                               //{
                                               //    debugStr += buffer[i] + " ";
                                               //    if (i % 16 == 0) debugStr += "\n";

            //}
            //Debug.WriteLine(debugStr);



            // 解析导联列表

            String str = "信道解析:\n";

            byte[] myLabel           = new byte[16]; //标签
            byte[] transducerType    = new byte[80]; //传感器类型
            byte[] physicalDimension = new byte[8];  //物理量
            byte[] physicalMinimum   = new byte[8];  //最小物理量
            byte[] physicalMaximum   = new byte[8];  //最大物理量
            byte[] digitalMinimum    = new byte[8];  //最小数字量
            byte[] digitalMaximum    = new byte[8];  //最大数字量
            byte[] prefilterings     = new byte[80]; //滤波
            byte[] samplesDataRecord = new byte[8];  //每条记录的样本
            byte[] reserved          = new byte[32]; //保留位

            List <byte[]> signalInfo = new List <byte[]>();

            signalInfo.Add(myLabel);
            signalInfo.Add(transducerType);
            signalInfo.Add(physicalDimension);
            signalInfo.Add(physicalMinimum);
            signalInfo.Add(physicalMaximum);
            signalInfo.Add(digitalMinimum);
            signalInfo.Add(digitalMaximum);
            signalInfo.Add(prefilterings);
            signalInfo.Add(samplesDataRecord);
            signalInfo.Add(reserved);


            int currentPoint = 0;

            for (int a = 0; a < signalInfo.Count; a++)
            {
                signalInfo[a] = buffer.Skip(currentPoint).Take(signalInfo[a].Length).ToArray();
                currentPoint += signalInfo[a].Length;
            }

            str += $"标签:[ {Ascii2Str(signalInfo[0]).Trim()} ]\n" +
                   $"传感器类型:[{Ascii2Str(signalInfo[1]).Trim()}]\n" +
                   $"物理量:[{Ascii2Str(signalInfo[2]).Trim()}]\n" +
                   $"最小物理量:[{Ascii2Str(signalInfo[3]).Trim()}]\n" +
                   $"最大物理量:[{Ascii2Str(signalInfo[4]).Trim()}]\n" +
                   $"最小数字量:[{Ascii2Str(signalInfo[5]).Trim()}]\n" +
                   $"最大数字量:[{Ascii2Str(signalInfo[6]).Trim()}]\n" +
                   $"滤波:[{Ascii2Str(signalInfo[7]).Trim()}]\n" +
                   $"每条记录的样本:[{Ascii2Str(signalInfo[8]).Trim()}]\n" +
                   $"保留位:[{Ascii2Str(signalInfo[9]).Trim()}]\n";


            MessageBox.Show(str);



            this._header.parseSignals(buffer, encoding);
        }
Пример #33
0
        /// <summary>
        /// 解析文件头
        /// </summary>
        /// <param name="fs">文件流</param>
        /// <param name="encoding">编码</param>
        private void parseHeader(FileStream fs, Encoding encoding)
        {
            // 读取文件头
            var buffer = new byte[HEADER_LENGTH];


            fs.Read(buffer, 0, buffer.Length);
            String str = "头文件输出:\n";
            int    i   = 0;

            //foreach (byte b in buffer)
            //{
            //    i++;
            //    str += b.ToString() + "  ";
            //    if (i % 16 == 0) str += "\n";

            //}

            byte[]        version                = new byte[8];
            byte[]        patientInfo            = new byte[80];
            byte[]        recordingInfo          = new byte[80];
            byte[]        recordDate             = new byte[8];
            byte[]        recordTime             = new byte[8];
            byte[]        headerRecordByteLength = new byte[8];
            byte[]        reserved               = new byte[44];
            byte[]        dataRecrdNumber        = new byte[8];
            byte[]        durationOfDataRecord   = new byte[8];
            byte[]        signalNumber           = new byte[4];
            List <byte[]> headerInfos            = new List <byte[]>();

            headerInfos.Add(version);
            headerInfos.Add(patientInfo);
            headerInfos.Add(recordingInfo);
            headerInfos.Add(recordDate);
            headerInfos.Add(recordTime);
            headerInfos.Add(headerRecordByteLength);
            headerInfos.Add(reserved);
            headerInfos.Add(dataRecrdNumber);
            headerInfos.Add(durationOfDataRecord);
            headerInfos.Add(signalNumber);



            int currentPosition = 0;

            for (int j = 0; j < headerInfos.Count; j++)
            {
                headerInfos[j]   = buffer.Skip(currentPosition).Take(headerInfos[j].Length).ToArray();
                currentPosition += headerInfos[j].Length;
            }



            str += $"数据版本号:[ {Ascii2Str(headerInfos[0]).Trim()} ]\n" +
                   $"患者信息:[{Ascii2Str(headerInfos[1]).Trim()}]\n" +
                   $"记录信息:[{Ascii2Str(headerInfos[2]).Trim()}]\n" +
                   $"记录日期:[{Ascii2Str(headerInfos[3]).Trim()}]\n" +
                   $"记录时间:[{Ascii2Str(headerInfos[4]).Trim()}]\n" +
                   $"头记录字节长度:[{Ascii2Str(headerInfos[5]).Trim()}]\n" +
                   $"保留区:[{Ascii2Str(headerInfos[6]).Trim()}]\n" +
                   $"数据记录数:[{Ascii2Str(headerInfos[7]).Trim()}]\n" +
                   $"数据记录周期:[{Ascii2Str(headerInfos[8]).Trim()}]\n" +
                   $"信道数量:[{Ascii2Str(headerInfos[9]).Trim()}]\n";


            //for (int currentPosition = 0; currentPosition <buffer.Length ; currentPosition++) {


            //}
            Debug.WriteLine(str);
            MessageBox.Show(str);
            // 解析文件头
            this._header = new MyEDFileHeader(buffer, encoding);
        }