GetString() 공개 메소드

public GetString ( byte bytes, int byteIndex, int byteCount ) : string
bytes byte
byteIndex int
byteCount int
리턴 string
예제 #1
1
 //Connect to the client
 public void connect()
 {
     if (!clientConnected)
     {
         IPAddress ipAddress = IPAddress.Any;
         TcpListener listener = new TcpListener(ipAddress, portSend);
         listener.Start();
         Console.WriteLine("Server is running");
         Console.WriteLine("Listening on port " + portSend);
         Console.WriteLine("Waiting for connections...");
         while (!clientConnected)
         {
             s = listener.AcceptSocket();
             s.SendBufferSize = 256000;
             Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
             byte[] b = new byte[65535];
             int k = s.Receive(b);
             ASCIIEncoding enc = new ASCIIEncoding();
             Console.WriteLine("Received:" + enc.GetString(b, 0, k) + "..");
             //Ensure the client is who we want
             if (enc.GetString(b, 0, k) == "hello" || enc.GetString(b, 0, k) == "hellorcomplete")
             {
                 clientConnected = true;
                 Console.WriteLine(enc.GetString(b, 0, k));
             }
         }
     }
 }
예제 #2
0
파일: PicManager.cs 프로젝트: Aohzan/Picsi
        public Pic GetInfos(string path)
        {
            // Pour décoder les propriétés de l'image
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

            var pic = new Pic
            {
                Path      = path,
                Name      = path.Substring(path.LastIndexOf(@"\") + 1),
                Extension = path.Substring(path.LastIndexOf(@".") + 1)
            };


            using (Image image = new Bitmap(pic.Path))
            {
                pic.Width  = image.Width;
                pic.Height = image.Height;
                if (image.Tag != null)
                {
                    pic.Tag = image.Tag.ToString();
                }
                pic.Manufacturer = encoding.GetString(image.GetPropertyItem(271).Value).Replace("\0", "");
                pic.Model        = encoding.GetString(image.GetPropertyItem(272).Value).Replace("\0", "");
                var date = encoding.GetString(image.GetPropertyItem(306).Value).Replace("\0", "");
                pic.ShotDate = DateTime.ParseExact(date, "yyyy:MM:dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

                image.Dispose();
            }
            return(pic);
        }
예제 #3
0
    void commslisten()
    {
        ///////////////////////////////////////////////////////
        ////// Main function which waits for a msg from an user
        ///////////////////////////////////////////////////////
        IPEndPoint EP;

        listener = new UdpClient(8000);
        EP       = new IPEndPoint(IPAddress.Any, 8000);
        byte[]   rec = new byte[100];
        string[] buffer;
        string   data;

        Thread.Sleep(1000);
        while (done)
        {
            try {
                print("WAITING FOR INCOMING MESSAGES");
                rec  = listener.Receive(ref EP);                // blocking call !!!
                data = encode.GetString(rec);
                print("REC:" + data);
                buffer = data.Split();
                if (buffer[0] == "make")
                {
                    init(buffer[1]);
                }
                print("CER:");
                Thread.Sleep(10);
            } catch (Exception e) {
                print("MAIN::" + e.ToString());
            }
        }
    }
        public object Search(queryrequest xml)
        {
            SemWeb.Query.Query query = null;

            string q = string.Empty;

            try
            {
                query = new SparqlEngine(new StringReader(xml.query));
            }
            catch (QueryFormatException ex)
            {
                var malformed = new malformedquery();

                malformed.faultdetails = ex.Message;

                return malformed;
            }

            // Load the data from sql server
            SemWeb.Stores.SQLStore store;

            string connstr = ConfigurationManager.ConnectionStrings["SemWebDB"].ConnectionString;

            DebugLogging.Log(connstr);

            store = (SemWeb.Stores.SQLStore)SemWeb.Store.CreateForInput(connstr);

            //Create a Sink for the results to be writen once the query is run.
            MemoryStream ms = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
            QueryResultSink sink = new SparqlXmlQuerySink(writer);

            try
            {
                // Run the query.
                query.Run(store, sink);

            }
            catch (Exception ex)
            {
                // Run the query.
                query.Run(store, sink);
                DebugLogging.Log("Run the query a second time");
                DebugLogging.Log(ex.Message);

            }
            //flush the writer then  load the memory stream
            writer.Flush();
            ms.Seek(0, SeekOrigin.Begin);

            //Write the memory stream out to the response.
            ASCIIEncoding ascii = new ASCIIEncoding();
            DebugLogging.Log(ascii.GetString(ms.ToArray()).Replace("???", ""));
            writer.Close();

            DebugLogging.Log("End of Processing");

            return SerializeXML.DeserializeObject(ascii.GetString(ms.ToArray()).Replace("???", ""), typeof(sparql)) as sparql;
        }
예제 #5
0
        //验证客户端登录信息
        private string VerifyLogin(byte[] message)
        {
            byte[] name     = new byte[message[0]];
            byte[] password = new byte[message[1]];
            for (int i = 2; i < message[0] + 2; i++)
            {
                name[i - 2] = message[i];
            }

            for (int k = message[0] + 2; k < message[1] + message[0] + 2; k++)
            {
                password[k - message[0] - 2] = message[k];
            }

            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();

            string UserName     = asciiEncoding.GetString(name);
            string UserPassword = asciiEncoding.GetString(password);

            UserServer user     = new UserServer();
            string     sqlSelct = "select UserAuthority from user where UserName='******' and UserPassWord= '******'";

            string    UserAuthority = null;
            DataTable dt            = db.Select(sqlSelct);

            if (dt != null)
            {
                UserAuthority = dt.Rows[0][0].ToString();
            }
            return(UserAuthority);
        }
예제 #6
0
 /// <summary>
 /// Wrap a message as a CTCP command
 /// </summary>
 /// <param name="message">
 /// The message.
 /// </param>
 /// <param name="ctcpCommand">
 /// The CTCP command.
 /// </param>
 /// <returns>
 /// The <see cref="string"/>.
 /// </returns>
 public static string SetupForCtcp(this string message, string ctcpCommand)
 {
     var asc = new ASCIIEncoding();
     byte[] ctcp = { Convert.ToByte(1) };
     return asc.GetString(ctcp) + ctcpCommand.ToUpper()
            + (message == string.Empty ? string.Empty : " " + message) + asc.GetString(ctcp);
 }
예제 #7
0
        /// <summary>
        /// Respuesta a un comando AT
        /// </summary>
        /// <param name="arraydebytes">Arreglo que llega desde el puerto serial</param>
        public ATCommandResponse(byte[] arraydebytes)
        {
            //El arreglo llega con varios elementos de mas
            // arraydebytes[0] --> es el caracter delimitador
            // arraydebytes[1] --> es el caracter MSB
            // arraydebytes[2] --> es el caracter LSB
            // arraydebytes[3] --> es el caracter Frame Type --> en este caso es igual a 0x88 para respuestas a Comandos AT
            // arraydebytes[4] --> es el caracter Frame ID
            // arraydebytes[arraydebytes.Length -1] --> es el ultimo caracter: es el Checksum.

            //this.API_ID_Specific_Data --> se debe llenar con los datos específicos del paquete en cuestion, excluyendo lo de arriba.
            setFrameSpecificData(arraydebytes);

            // arraydebytes[4] --> es el caracter Frame ID
            this.FrameID = arraydebytes[4];

            // arraydebytes[3] --> es el caracter Frame Type --> en este caso es igual a 0x88 para respuestas a Comandos AT
            if (arraydebytes[3] == (byte)API_Xbee.Commands.TypeApiFramesNames.AT_Command_Response)
            {
                this.API_Identifier = API_Xbee.Commands.TypeApiFramesNames.AT_Command_Response;

                System.Text.ASCIIEncoding codificador = new System.Text.ASCIIEncoding();


                byte[] comandoatrespuesta = new byte[2];
                comandoatrespuesta[0] = this.API_ID_Specific_Data[0];
                comandoatrespuesta[1] = this.API_ID_Specific_Data[1];

                ATCommand = codificador.GetString(comandoatrespuesta);

                ATCommandStatus = this.API_ID_Specific_Data[2] == 0x00 ? true : false;


                byte[] nuevacadenasalida = new byte[this.API_ID_Specific_Data.Length - 3];

                for (int i = 0; i < nuevacadenasalida.Length; i++)
                {
                    nuevacadenasalida[i] = this.API_ID_Specific_Data[i + 3];
                }

                CadenaRespuesta = codificador.GetString(nuevacadenasalida);

                if (arraydebytes[1] != this.LengthMSB)
                {
                    throw new Exception("MSB Diferente");
                }
                if (arraydebytes[2] != this.LengthLSB)
                {
                    throw new Exception("LSB Diferente");
                }
                if (arraydebytes[arraydebytes.Length - 1] != this.CheckSum)
                {
                    throw new Exception("Checksum Diferente");
                }
            }
            else
            {
                throw new Exception("No es Respuesta a Comando AT");
            }
        }
예제 #8
0
        public void getv3dinfo(string filenamedialog)
        {
            if (File.Exists(filenamedialog))
            {
                v3dfilename = filenamedialog;
                FileStream   fs = File.OpenRead(v3dfilename);
                BinaryReader br = new BinaryReader(fs);

                v3dfilesize = (int)fs.Length;
                fs.Position = 0;

                byte[] byteArray = new byte[5];
                byteArray = br.ReadBytes(5);
                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                v3dformat = enc.GetString(byteArray);

                fs.Position = 7;
                byte[] byteArray2 = new byte[3];
                byteArray2 = br.ReadBytes(3);
                v3dversion = enc.GetString(byteArray2);

                fs.Position = 40;
                v3dsizes[0] = br.ReadInt32();
                v3dsizes[1] = br.ReadInt32();
                v3dsizes[2] = br.ReadInt32();

                v3dscales[0] = br.ReadDouble();
                v3dscales[1] = br.ReadDouble();
                v3dscales[2] = br.ReadDouble();

                fs.Position = 100;
                v3dbits     = br.ReadInt32();
                if (v3dbits == 0)
                {
                    v3dbits = 16;
                }
                v3dtime = br.ReadInt32();
                v3dpar  = br.ReadInt32();

                v3doffset = -(v3dbits / 8) * v3dsizes[0] * v3dsizes[1] * v3dsizes[2] + v3dfilesize;

                br.Close();
                fs.Close();

                info  = "File length : " + v3dfilesize + "\r\n";
                info += "File format : " + v3dformat + "\r\n";
                info += "File version : " + v3dversion + "\r\n";
                info += "Volume size : " + v3dsizes[0] + " " + v3dsizes[1] + " " + v3dsizes[2] + "\r\n";
                info += "Volume scales : " + v3dscales[0] + " " + v3dscales[1] + " " + v3dscales[2] + "\r\n";
                info += "Volume bits : " + v3dbits + "\r\n";
                info += "Volume offset : " + v3doffset + "\r\n";
            }
            else
            {
                //"File not Found";
            }
        }
예제 #9
0
    public string ReadString()
    {
        int offset = m_ReadPos;

        while (m_DataBuffer[m_ReadPos++] != 0)
        {
        }

        return(_converter.GetString(m_DataBuffer, offset, m_ReadPos - offset - 1));
    }
예제 #10
0
        //2D Lable 打印方式
        public static void Print2DLabel(string pinterName, System.Collections.ArrayList printValueList)
        {
            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
            //order
            byte[] byteArray = new byte[] { (byte)27 };
            string Esc       = asciiEncoding.GetString(byteArray);

            DOCINFO di        = new DOCINFO();
            int     pcWritten = 0;

            di.pDocName  = "CT4i";
            di.pDataType = "RAW";

            //打开打印机
            string PrinterName = pinterName;
            int    lhPrinter   = openPrinter(PrinterName);
            int    lineCount   = 0; //标记现在打印的是第几行
            string printValueA = string.Empty;

            //StartDocPrinter((IntPtr)lhPrinter, 1, ref di);
            //StartPagePrinter((IntPtr)lhPrinter);

            //打印数据,两行算一个条码,打完要SATO结束指令,传过来的值的行数一定是2的倍数
            for (int i = 0; i < printValueList.Count; i++)
            {
                lineCount++;
                if (lineCount == 1)
                {
                    StartDocPrinter((IntPtr)lhPrinter, 1, ref di);
                    StartPagePrinter((IntPtr)lhPrinter);
                    //SATO 打印机开始指令,必须有
                    printValueA = asciiEncoding.GetString(new byte[] { (byte)2 }) + Esc + "A";
                    WritePrinter((IntPtr)lhPrinter, printValueA, printValueA.Length, ref pcWritten);
                }
                printValueA = printValueList[i].ToString().Replace("\r\n", "");
                WritePrinter((IntPtr)lhPrinter, printValueA, printValueA.Length, ref pcWritten);

                if (lineCount == 2)
                {
                    lineCount   = 0;
                    printValueA = Esc + "Q1" + Esc + "Z" + asciiEncoding.GetString(new byte[] { (byte)3 });
                    WritePrinter((IntPtr)lhPrinter, printValueA, printValueA.Length, ref pcWritten);
                    EndPagePrinter((IntPtr)lhPrinter);
                    EndDocPrinter((IntPtr)lhPrinter);
                    //ClosePrinter((IntPtr)lhPrinter);
                }
            }

            //SATO打印结束指令
            //printValueA = Esc + "Q1" + Esc + "Z" + asciiEncoding.GetString(new byte[] { (byte)3 });
            //WritePrinter((IntPtr)lhPrinter, printValueA, printValueA.Length, ref pcWritten);
            //EndPagePrinter((IntPtr)lhPrinter);
            //EndDocPrinter((IntPtr)lhPrinter);
            ClosePrinter((IntPtr)lhPrinter);
        }
예제 #11
0
        /// <summary>
        /// 选择水位数据文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBrowser_Click(object sender, EventArgs e)
        {
            if (ofdData.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.DataFile    = ofdData.FileName;
                txtDataFile.Text = DataFile;
                //读取数据的开始时间和结束时间
                //StreamReader sr = new StreamReader(this.DataFile);
                //string firstline = sr.ReadLine();
                //string lastline = "";
                //string s = "";
                //while ((s = sr.ReadLine()) != null)
                //{
                //    lastline = s;
                //}
                //sr.Close();

                //使用二进制读取方法,提高运行速度
                byte[]     start = new byte[30];
                byte[]     end   = new byte[30];
                int        b;
                FileStream fs = new FileStream(this.DataFile, FileMode.Open);
                fs.Read(start, 0, start.Length);
                fs.Seek(end.Length * -1, SeekOrigin.End);
                fs.Read(end, 0, end.Length);
                long nlength = fs.Length;
                fs.Close();
                System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
                String ss = ASCII.GetString(start);
                String ee = ASCII.GetString(end);

                //2002120100 28.711
                string sStart = ss.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[0];
                //一行水位数据的长度,含\R\N
                nWaterLineLen = ss.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)[0].Length + 2;
                if (nlength / nWaterLineLen > 365 * 24 * 11)
                {
                    MessageBox.Show("单次计算的数据量不能超过11年,请手动分开计算!");
                    return;
                }
                string[] sEnds = ee.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                string   sEnd  = sEnds[sEnds.Length - 1].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[0];
                txtStartTime.Text = sStart;
                txtEndTime.Text   = sEnd;
            }
            else
            {
                this.DataFile     = "";
                txtDataFile.Text  = "";
                txtStartTime.Text = "";
                txtEndTime.Text   = "";
            }
        }
예제 #12
0
        public TRK(Stream Data)
        {
            m_Reader = new FileReader(Data, false);
            string DataStr = "";
            string[] Elements;

            ASCIIEncoding Enc = new ASCIIEncoding();
            string MagicNumber = Enc.GetString(m_Reader.ReadBytes(4));

            if (!MagicNumber.Equals("2DKT", StringComparison.InvariantCultureIgnoreCase) && !MagicNumber.Equals("TKDT", StringComparison.InvariantCultureIgnoreCase))
                throw new HitException("Invalid TrackData header - TRK.cs");

            if (MagicNumber.Equals("2DKT", StringComparison.InvariantCultureIgnoreCase))
            {
                DataStr = Enc.GetString(m_Reader.ReadBytes((int)m_Reader.ReadUInt32()));
                Elements = DataStr.Split(',');
            }
            else
                Elements = Enc.GetString(m_Reader.ReadToEnd()).Split(',');

            m_Version = int.Parse(Elements[1], NumberStyles.Integer);
            TrackName = Elements[2];

            if (!Elements[3].Equals("", StringComparison.InvariantCultureIgnoreCase))
                SoundID = uint.Parse(Elements[3].Replace("0x", ""), NumberStyles.HexNumber);
            else
                SoundID = 0;

            if (Elements[5].Equals("\r\n", StringComparison.InvariantCultureIgnoreCase))
                return;

            if (!Elements[5].Equals("", StringComparison.InvariantCultureIgnoreCase))
                Argument = (HITTrackArguments)Enum.Parse(typeof(HITTrackArguments), Elements[5]);

            if (!Elements[7].Equals("", StringComparison.InvariantCultureIgnoreCase))
                ControlGroup = (HITControlGroup)Enum.Parse(typeof(HITControlGroup), Elements[7]);

            if (!Elements[(m_Version != 2) ? 11 : 12].Equals("", StringComparison.InvariantCultureIgnoreCase))
                DuckingPriority = int.Parse(Elements[(m_Version != 2) ? 11 : 12], NumberStyles.Integer);

            if (!Elements[(m_Version != 2) ? 12 : 13].Equals("", StringComparison.InvariantCultureIgnoreCase))
                Looped = (int.Parse(Elements[(m_Version != 2) ? 12 : 13], NumberStyles.Integer) != 0) ? true : false;

            if (!Elements[(m_Version != 2) ? 13 : 14].Equals("", StringComparison.InvariantCultureIgnoreCase))
                Volume = int.Parse(Elements[(m_Version != 2) ? 13 : 14], NumberStyles.Integer);

            m_Reader.Close();
        }
예제 #13
0
파일: Program.cs 프로젝트: gauee/CoViVo
        static void Main(string[] args)
        {
            Text avt;
            avt = new Text();
            avt.messageCode = 5;
            avt.messageNumber = 1000;

            avt.text = "kuba";

            byte[] b = Util.Wrap(avt);
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            Console.WriteLine(encoding.GetString(b));
            Message msg = Util.Unwrap(b);
            if (msg is Text)
            {
                Text at = (Text)msg;
                Console.WriteLine(at.messageCode);
                Console.WriteLine(at.messageNumber);
                Console.WriteLine(at.text);
                Console.WriteLine();
                Console.ReadKey();
            }
            else {
                Console.WriteLine("Nieudane typowanie obiektu.");
            }
        }
예제 #14
0
        private void AddTextFileToDynamicData(string key, HttpPostedFileBase file)
        {
            var buffer = new byte[file.ContentLength];

            file.InputStream.Read(buffer, 0, file.ContentLength);
            System.Text.Encoding enc;
            string s = null;

            if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF)
            {
                enc = new System.Text.ASCIIEncoding();
                s   = enc.GetString(buffer, 3, buffer.Length - 3);
            }
            else if (buffer[0] == 0xFF && buffer[1] == 0xFE)
            {
                enc = new System.Text.UnicodeEncoding();
                s   = enc.GetString(buffer, 2, buffer.Length - 2);
            }
            else
            {
                enc = new System.Text.ASCIIEncoding();
                s   = enc.GetString(buffer);
            }

            pythonModel.DictionaryAdd(key, s);
        }
예제 #15
0
        public String GetString()
        {
            System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
            String StringMessage            = ASCII.GetString(m_Data);

            return(StringMessage);
        }
예제 #16
0
        static void Main(string[] args)
        {
            RSACryptoServiceProvider MyRsa = new RSACryptoServiceProvider();

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); //diziyi ascii kodlara dönüştürüyoruz.
            string data = "Ferdi KOCA Bilgi guvenligi  ve kriptoloji odevi";      //şifrelemek istediğim mesaj

            Byte[] newdata   = encoding.GetBytes(data);                           //mesajı byte çeviriyoruz.
            Byte[] encrypted = MyRsa.Encrypt(newdata, false);
            Console.WriteLine("Şifrelenmiş Metin  ");
            for (int i = 0; i < encrypted.Length; i++)
            {
                Console.Write("{0} ", encrypted[i]);
            }
            Console.WriteLine();
            Byte[] decrypted = MyRsa.Decrypt(encrypted, false); //decrypt
            Console.WriteLine("Çözülmüş Metin:  ");
            string dData = encoding.GetString(decrypted);       //bytlerı diziye geri çeviriyoruz.

            for (int i = 0; i < decrypted.Length; i++)
            {
                Console.Write("{0}", dData[i]);
            }
            Console.ReadKey();
        }
예제 #17
0
        /// <summary>
        /// Reads a string. It is assumed that a MTF_MEDIA_ADDRESS structure is next in the stream.
        /// </summary>
        public string ReadString(long StartPosition, EStringType Type)
        {
            long oldpos = BaseStream.Position;

            ushort sz  = ReadUInt16();
            long   off = StartPosition + ReadUInt16();

            BaseStream.Seek(off, System.IO.SeekOrigin.Begin);
            string str;

            if (Type == EStringType.ANSI)
            {
                byte[] bytes = ReadBytes(sz);
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                str = encoding.GetString(bytes);
            }
            else if (Type == EStringType.Unicode)
            {
                byte[] bytes = ReadBytes(sz);
                System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
                str = encoding.GetString(bytes);
            }
            else
            {
                str = "";
            }

            BaseStream.Seek(oldpos + 4, System.IO.SeekOrigin.Begin);

            return(str);
        }
예제 #18
0
파일: Logging.cs 프로젝트: JoJo777/TTK.SP
        internal static void WriteToLog(SPWeb web, string message)
        {
            ASCIIEncoding enc = new ASCIIEncoding();
            UnicodeEncoding uniEncoding = new UnicodeEncoding();

            string errors = message;

            SPFile files = web.GetFile("/" + DocumentLibraryName + "/" + LogFileName);

            if (files.Exists)
            {
                byte[] fileContents = files.OpenBinary();
                string newContents = enc.GetString(fileContents) + Environment.NewLine + errors;
                files.SaveBinary(enc.GetBytes(newContents));
            }
            else
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (StreamWriter sw = new StreamWriter(ms, uniEncoding))
                    {
                        sw.Write(errors);
                    }

                    SPFolder LogLibraryFolder = web.Folders[DocumentLibraryName];
                    LogLibraryFolder.Files.Add(LogFileName, ms.ToArray(), false);
                }
            }

            web.Update();
        }
예제 #19
0
 private string AscCodeToChr(int AsciiCode)
 {
     System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
     byte[] byteArray = new byte[] { (byte)AsciiCode };
     string strCharacter = asciiEncoding.GetString(byteArray);
     return (strCharacter);
 }
예제 #20
0
파일: Server.cs 프로젝트: Fun-User/FunBox
        public void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();

            byte[] message = new byte[4096];
            int bytesRead;

            while (true)
            {
                bytesRead = 0;
                try
                {
                    bytesRead = clientStream.Read(message, 0, 4096);

                }
                catch
                {
                    break;
                }

                if (bytesRead == 0)
                {
                    break;
                }
                ASCIIEncoding encoder = new ASCIIEncoding();
                String output = encoder.GetString(message, 0, bytesRead);
                System.Diagnostics.Debug.WriteLine(output);
                putTextDisplay(output);

            }

            tcpClient.Close();
        }
예제 #21
0
파일: Logging.cs 프로젝트: JoJo777/TTK.SP
        internal static void WriteToLog(SPContext context, string message)
        {
            context.Web.AllowUnsafeUpdates = true;

            ASCIIEncoding enc = new ASCIIEncoding();
            UnicodeEncoding uniEncoding = new UnicodeEncoding();

            SPFile files = context.Web.GetFile("/" + DocumentLibraryName + "/" + LogFileName);

            if (files.Exists)
            {
                byte[] fileContents = files.OpenBinary();
                string newContents = enc.GetString(fileContents) + Environment.NewLine + message;
                files.SaveBinary(enc.GetBytes(newContents));
            }
            else
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (StreamWriter sw = new StreamWriter(ms, uniEncoding))
                    {
                        sw.Write(message);
                    }

                    SPFolder LogLibraryFolder = SPContext.Current.Web.Folders[DocumentLibraryName];
                    LogLibraryFolder.Files.Add(LogFileName, ms.ToArray(), false);
                }
            }

            files.Update();

            context.Web.AllowUnsafeUpdates = false;
        }
예제 #22
0
        // RECEIVE DATA FROM SERVER     --string--
        public void ReceiveData()
        {
            while (true)
            {
                TcpClient tcpClient = (TcpClient)client;
                NetworkStream clientStream = tcpClient.GetStream();

                byte[] DataRecived = new byte[4096];
                int bytesRead;

                //Receive Data
                bytesRead = 0;
                try
                {
                    //Blocks LOOP until a Server sends Data
                    bytesRead = clientStream.Read(DataRecived, 0, 4096);
                    clientStream.Flush();
                }
                catch
                {
                    //a socket error has occured
                    break;
                 }
                 if (bytesRead == 0)
                 {
                    //the Server has disconnected the Player
                    break;
                 }
                    //message has successfully been received
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    strRecivedData = (encoder.GetString(DataRecived, 0, bytesRead));
            }//loop
        }
예제 #23
0
 public bool Connect(string address, int port, string token)
 {
     Disconnect();
     try
     {
         lock (m_lock)
         {
             m_client = new TcpClient();
             m_client.Connect(address, port);
             if (token.Length < TOKEN_SIZE)
                 for (int i = token.Length; i < TOKEN_SIZE; ++i)
                     token += " ";
             else if (token.Length > TOKEN_SIZE)
                 token = token.Substring(0, TOKEN_SIZE);
             var stream = m_client.GetStream();
             var ascii = new ASCIIEncoding();
             var tokenBytes = ascii.GetBytes(token);
             stream.Write(tokenBytes, 0, tokenBytes.Length);
             tokenBytes = new byte[TOKEN_SIZE];
             var tokenSize = stream.Read(tokenBytes, 0, TOKEN_SIZE);
             if (tokenSize == TOKEN_SIZE)
             {
                 m_token = ascii.GetString(tokenBytes);
                 return true;
             }
         }
     }
     catch { }
     Disconnect();
     return false;
 }
 public IObservable<IList<string>> IdentitiesActivated(IScheduler scheduler)
 {
     return Observable.Create<IList<string>>(
         o =>
             {
                 _logger.Debug("Starting Bluetooth listener...");
                 _listener.Start();
                 _logger.Debug("Bluetooth listener started.");
                 var encoder = new ASCIIEncoding();
                 try
                 {
                     _logger.Debug("_listener.AcceptBluetoothClient();");
                     var bluetoothClient = _listener.AcceptBluetoothClient();
                     _logger.Debug("bluetoothClient.GetStream();");
                     var ns = bluetoothClient.GetStream();
                     //TODO: Should this be a recursive call, or should I just continue on the same scheduler path? -LC
                     return ns.ToObservable(1, scheduler)
                              .Aggregate(new List<byte>(),
                                         (acc, cur) =>
                                         {
                                             acc.Add(cur);
                                             return acc;
                                         })
                              .Select(bytes=>encoder.GetString(bytes.ToArray()))
                              .Select(data=>data.Split('\n'))
                              .Subscribe(o);
                 }
                 catch(Exception ex)
                 {
                     o.OnError(ex);
                     return Disposable.Empty;
                 }
             }).SubscribeOn(scheduler);
 }
예제 #25
0
        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            FileStream file = null;
            try
            {
                Console.WriteLine("Got file {0}\n", openFileDialog1.FileName);
                file = new FileStream(openFileDialog1.FileName, FileMode.Open);
                byte[] tool = new byte[file.Length];
                file.Read(tool, 0, (int)file.Length);
                ASCIIEncoding encoder = new ASCIIEncoding();

                // Get the asset id...
                String xml = encoder.GetString(tool, 0, tool.Length);
                XElement root = XElement.Parse(xml);
                String id = root.Attribute("assetId").Value;
                id += Convert.ToSingle(mNumber);
                mNumber += 1;

                root.SetAttributeValue("assetId", id);

                // Create the line
                String text = "@ASSET@|" + id + "|CuttingTool|--multiline--XXX\n" + root.ToString() +
                     "\n--multiline--XXX\n";
                adapter.Send(text);
                UpdateToolData(id);
            }
            catch (Exception)
            {
                Console.WriteLine("Failed to send file {0}",
                    openFileDialog1.FileName);
            }

            if (file != null)
                file.Close();
        }
예제 #26
0
        /// <summary>
        /// Returns the Uuid from a series of bytes
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="offset"></param>
        /// <returns></returns>
        public static string BytesToUuid(AppendableByteArray bytes, int offset)
        {
            byte[] uuid = bytes.GetSubarray(offset, UUID_LEN);

            ASCIIEncoding encoding = new ASCIIEncoding();
            return encoding.GetString(uuid);
        }
예제 #27
0
 public static string toString(byte[] dBytes)
 {
     string str;
     System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
     str = enc.GetString(dBytes);
     return str;
 }
예제 #28
0
        void ShowPicture()
        {
            string name = undoStack[current];

            Despatch(delegate() {
                lblFolder.Text = Path.GetFileName(Path.GetDirectoryName(name));
                lblDate.Text   = new FileInfo(name).LastWriteTime.Date.ToString("Y");
                lblName.Text   = Path.GetFileNameWithoutExtension(name);
                if (pictureBox1.Image != null)
                {
                    pictureBox1.Image.Dispose();
                }
                pictureBox1.Image    = Image.FromFile(name);
                DateTime dateCreated = new FileInfo(name).LastWriteTime;
                // Get the Date Created property
                //System.Drawing.Imaging.PropertyItem propertyItem = image.GetPropertyItem( 0x132 );
                System.Drawing.Imaging.PropertyItem propertyItem
                    = pictureBox1.Image.PropertyItems.FirstOrDefault(i => i.Id == 0x132);
                if (propertyItem != null)
                {
                    // Extract the property value as a String.
                    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                    string text = encoding.GetString(propertyItem.Value, 0, propertyItem.Len - 1);

                    // Parse the date and time.
                    System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
                    dateCreated = DateTime.ParseExact(text, "yyyy:MM:d H:m:s", provider);
                }
                lblFolder.Text = Path.GetFileName(Path.GetDirectoryName(name));
                lblDate.Text   = dateCreated.Date.ToString("Y");
                lblName.Text   = Path.GetFileNameWithoutExtension(name);
            });
        }
예제 #29
0
 public String[] ListReaders()
 {
     string[] readers;
     UInt32 pcchReaders = 0;
     SCardListReaders(context, null, null, ref pcchReaders);
     byte[] mszReaders = new byte[pcchReaders];
     SCardListReaders(context, null, mszReaders, ref pcchReaders);
     System.Text.ASCIIEncoding asc = new System.Text.ASCIIEncoding();
     String[] Readers = asc.GetString(mszReaders).Split('\0');
     if (Readers.Length > 2)
     {
         String[] res = new String[Readers.Length - 2];
         int j = 0;
         for (int i = 0; i < Readers.Length; i++)
         {
             if (Readers[i] != "" && Readers[i] != null)
             {
                 res[j] = Readers[i];
                 j++;
             }
         }
         readers = res;
         return readers;
     }
     else
     {
         readers = new String[0];
         return readers;
     }
 }
예제 #30
0
        public static string DoQuestion(string txt)
        {
            TcpClient client = new TcpClient();

            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000);

            try
            {
                client.Connect(serverEndPoint);

                NetworkStream clientStream = client.GetStream();

                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] buffer = encoder.GetBytes(txt);

                clientStream.ReadTimeout = 1000;
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();

                buffer = new Byte[128];
                int size = clientStream.Read(buffer, 0, buffer.Length);

                client.Close();
                return encoder.GetString(buffer, 0, buffer.Length);
            }
            catch
            {
                return "failed";
            }
        }
예제 #31
0
    private void HandleClientComm(object clientObj)
    {
        byte[]    message = new byte[4096];
        TcpClient client  = (TcpClient)clientObj;

        while (true)
        {
            var bytesRead = 0;

            try
            {
                bytesRead = client.GetStream().Read(message, 0, 4096);
            }
            catch
            {
                break;
            }

            if (bytesRead == 0)
            {
                break;
            }

            var encoding = new System.Text.ASCIIEncoding();
            receivedMessage = encoding.GetString(message);
        }
    }
예제 #32
0
        public static int Serialize(Kowhai.kowhai_node_t[] descriptor, byte[] data, out string target, Object getNameParam, GetSymbolName getName)
        {
            kowhai_get_symbol_name_t _getName = delegate(IntPtr param, UInt16 value)
            {
                return getName(getNameParam, value);
            };

            byte[] targetBuf;
            int targetBufferSize = 0x1000;
            int result;
            Kowhai.kowhai_tree_t tree;
            GCHandle h = GCHandle.Alloc(descriptor, GCHandleType.Pinned);
            tree.desc = h.AddrOfPinnedObject();
            GCHandle h2 = GCHandle.Alloc(data, GCHandleType.Pinned);
            tree.data = h2.AddrOfPinnedObject();
            do
            {
                targetBufferSize *= 2;
                targetBuf = new byte[targetBufferSize];
                result = kowhai_serialize(tree, targetBuf, ref targetBufferSize, IntPtr.Zero, _getName);
            }
            while (result == Kowhai.STATUS_TARGET_BUFFER_TOO_SMALL);
            h2.Free();
            h.Free();
            ASCIIEncoding enc = new ASCIIEncoding();
            target = enc.GetString(targetBuf, 0, targetBufferSize);
            return result;
        }
예제 #33
0
        private void btnCheckDate_Click(object sender, EventArgs e)
        {
            lstFilledFiles.Items.Clear();
            //webGeocode.Navigate(new Uri(@"file://c:\Images\geocode.html"));
            for (int i = 0; i < lstFiles.Items.Count; i++)
            {
                using (Image image = new Bitmap(lstFiles.Items[i].ToString()))
                {
                    PropertyItem[] propItems = image.PropertyItems;

                    int count = 0;
                    foreach (PropertyItem propItem in propItems)
                    {
                        //lstFiles.Items.Add(count + "   iD: 0x" + propItem.Id.ToString("x"));

                        if (propItem.Id == 0x9003) //id for date taken
                        {
                            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                            string propValue = encoding.GetString(propItems[count].Value);
                            if (string.IsNullOrEmpty(propValue) != true && propValue != "\0")
                            {
                                lstFilledFiles.Items.Add(Path.GetFileName(lstFiles.Items[i].ToString()) + "\t'" + propValue + "'");
                            }
                        }
                        count++;
                    }
                }
            }
        }
예제 #34
0
        //=========================================================================
        /// <summary>
        /// Get the text string found at this field id.
        /// </summary>
        /// <param name="fieldID">Message field id value. e.g. 9003</param>
        /// <returns>The string value</returns>
        //=========================================================================
        public string getTextField(int fieldID)
        {
            int    byteIndex = 0;
            int    msgType;
            int    iFld;
            string strField;

            msgType = fieldID / 1000;                                                           //fieldID / 1000 gives the message id
            iFld    = fieldID % 1000;
            if ((msgType == msg.msgType) &&                                                     // Check that the field corresponds to this msg
                (msgSpec[msgType - 1].fld[iFld - 1] == (int)TTypedValue.TBaseType.ITYPE_STR) && // Validate the type of this field within the message
                (msg.dataPtr.Length > 0))
            {
                //at this point we need to calc the total offset in the dataptr for this char[]
                if (iFld > 1)
                {
                    byteIndex = (int)calcOffset(fieldID);
                }
                int strSize = BitConverter.ToInt32(msg.dataPtr, byteIndex);                      //get the size of the char string
                byteIndex += (int)TTypedValue.typeSize[(int)TTypedValue.TBaseType.ITYPE_INT4];   //jump past the DIM=x 4 bytes
                strField   = ascii.GetString(msg.dataPtr, byteIndex, strSize);
            }
            else
            {
                string errorMsg = string.Format("Cannot retrieve string field {0} from msg {1}", iFld, msg.msgType);
                throw (new ApplicationException(errorMsg));
            }
            return(strField);
        }
예제 #35
0
        void DisplayMessageReceived(byte[] message)
        {
            ASCIIEncoding encoder = new ASCIIEncoding();
            string str = encoder.GetString(message, 0, message.Length);

            tbReceived.Text += str + "\r\n";
        }
예제 #36
0
    public void ImportBinding()
    {
        string       _playerPostfix = player.postfix;
        string       path           = Application.persistentDataPath + "\\Player" + _playerPostfix + ".bdg";
        StreamReader sr             = new StreamReader(path);
        string       raw            = sr.ReadLine();

        sr.Close();
        //DeCrypt Begin
        byte[] bytes = Convert.FromBase64String(raw);
        System.Text.ASCIIEncoding dec = new System.Text.ASCIIEncoding();
        string data = dec.GetString(bytes);

        //DeCrypt End
        int i = 0;

        string[] rawData = data.Split('|');
        foreach (string set in rawData)
        {
            string[] _data = set.Split(':');
            i++;
            if (i != binding.Count)
            {
                Enumerators.Action _action  = (Enumerators.Action)Convert.ToInt32(_data[0]);
                KeyCode            _keyCode = (KeyCode)Convert.ToInt32(_data[1]);
                binding[_action] = _keyCode;
                Helper();
            }
        }
    }
예제 #37
0
    public void LoadSli()
    {
        System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
        openFileDialog.InitialDirectory = Application.dataPath + "/Samples";
        var sel = "SLI Files (*.sli)|*.sli|";
        sel = sel.TrimEnd('|');
        openFileDialog.Filter = sel;
        openFileDialog.FilterIndex = 2;
        openFileDialog.RestoreDirectory = false;

        if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            try
            {
                var fileName = openFileDialog.FileName;
                if (fileName != null)
                {
                    var reader = new StreamReader(fileName);
                    string full = "";
                    while (!reader.EndOfStream)
                    {
                        full = reader.ReadLine();
                        System.Text.ASCIIEncoding Encoding = new System.Text.ASCIIEncoding();
                        var bytes = Encoding.GetBytes(full);
                        var text = Encoding.GetString(bytes);
                    }
                    reader.Close();
                }
            }
            catch { }

        }
    }
예제 #38
0
        public HttpMap(byte[] ByteHttpRequest)
        {
            string HttpRequest = encoding.GetString(ByteHttpRequest);

            try
            {
                int    IndexHeaderEnd;
                string Header;

                // Si la taille de requête est supérieur ou égale à 1460, alors toutes la chaine est l'entête Http
                if (HttpRequest.Length <= 1460)
                {
                    Header = HttpRequest;
                }
                else
                {
                    IndexHeaderEnd = HttpRequest.IndexOf("\r\n\r\n");
                    Header         = HttpRequest.Substring(0, IndexHeaderEnd);
                    Data           = ByteHttpRequest.Skip(IndexHeaderEnd + 4).ToArray();
                }

                HttpHeaderParse(Header);
            }
            catch (Exception)
            { }
        }
예제 #39
0
    void ReadUDP()
    {
        IPEndPoint EP;

        listener = new UdpClient(8888);
        EP       = new IPEndPoint(IPAddress.Any, 8888);
        byte[]   rec = new byte[100];
        string[] buffer;
        string   data;

        Thread.Sleep(1000);
        while (done)
        {
            try {
                print("WAITING FOR INCOMING UDP PCD");
                rec  = listener.Receive(ref EP);                // blocking call !!!
                data = encode.GetString(rec);
                print("REC:" + data);
                buffer = data.Split();
                print("CER:");
                Thread.Sleep(10);
            } catch (Exception e) {
                print("MAIN::" + e.ToString());
            }
        }
    }
예제 #40
0
        private static void HandleClient(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            EndPoint remote = tcpClient.Client.RemoteEndPoint;

            NetworkStream clientStream = tcpClient.GetStream();
            int bytesRead;
            byte[] message = new byte[tcpClient.ReceiveBufferSize];

            ASCIIEncoding encoder = new ASCIIEncoding();

            while (true)
            {
                bytesRead = 0;
                string strMessage = "";
                try
                {
                    bytesRead = clientStream.Read(message, 0, tcpClient.ReceiveBufferSize);

                    strMessage = encoder.GetString(message, 0, bytesRead);
                    Console.WriteLine(String.Format("{1} just sent: {0}", strMessage, remote.ToString()));
                }
                catch
                {
                    //error = true;
                    break;
                }

                if (bytesRead == 0)
                    break;

            }
        }
예제 #41
0
        private void HandleClientComm(object client)
        {
            using (TcpClient tcpClient = (TcpClient)client)
            {
                NetworkStream clientStream = tcpClient.GetStream();

                byte[] message = new byte[Constants.TCP_MESSAGE_SIZE];
                int bytesRead;

                while (true)
                {
                    bytesRead = 0;

                    try
                    {
                        bytesRead = clientStream.Read(message, 0, Constants.TCP_MESSAGE_SIZE);
                    }
                    catch
                    {
                        break;
                    }

                    // disconnect
                    if (bytesRead == 0)
                        break;

                    ASCIIEncoding encoder = new ASCIIEncoding();
                    System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
                }
            }
        }
예제 #42
0
 public string GetMemberNameFromValue(byte memberValue) {
     byte[] nameBuffer = new byte[(int)NetCDF.netCDF_limits.NC_MAX_NAME+1];
     ASCIIEncoding encoder = new ASCIIEncoding();
     NcCheck.Check(NetCDF.nc_inq_enum_ident(groupId, myId, (Int64) memberValue, nameBuffer));
     string buf = encoder.GetString(nameBuffer);
     return buf.Substring(0, buf.IndexOf('\0'));
 }
예제 #43
0
        public static string ByteToStr(byte[] dBytes)
        {
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            string str = enc.GetString(dBytes);

            return(str);
        }
예제 #44
0
    // Update is called once per frame
    void Update()
    {
        if (server.Pending())
        {
            //print ("comunica com cliente");
            cliente = server.AcceptSocket();
            cliente.Blocking = false;

            // operacoes de escrita e leitura com cliente
            byte [] mensagem = new byte[1024];
            cliente.Receive (mensagem); //leitura da mensagem enviada pelo cliente
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding ();
            strMessage = encoding.GetString (mensagem).ToString (); // string contendo mensagem recebida do cliente
            //print (strMessage);

            //prepara mensagem para envio
            byte[] envioBuffer = new byte[4];
            envioBuffer[0] = (byte)'a';
            envioBuffer[1] = (byte)'c';
            envioBuffer[2] = (byte)'k';
            envioBuffer[3] = 10;
            cliente.Send(envioBuffer); //envia mensagem ao cliente

        }

        // utiliza a mensagem recebida do cliente que foi armazenada
        // na variavel strMessage para atuar no objeto Cube da cena
        if (strMessage.Contains("noventa")) {
            meuservo.GetComponent<Servo_Motor_Limitado>().rotacao = 90; // rotaciona o servo em 90 graus
        }
    }
예제 #45
0
파일: FTP.cs 프로젝트: DigixDev/FTP
        private string ResponseMsg()
        {
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            byte[] serverbuff             = new Byte[1024];
            int    count = 0;

            while (true)
            {
                byte[] buff  = new Byte[2];
                int    bytes = stream.Read(buff, 0, 1);
                if (bytes == 1)
                {
                    serverbuff[count] = buff[0];
                    count++;

                    if (buff[0] == '\n')
                    {
                        break;
                    }
                }
                else
                {
                    break;
                };
            }
            ;
            string retval = enc.GetString(serverbuff, 0, count);

            Console.WriteLine(" READ:" + retval);
            retValue = Int32.Parse(retval.Substring(0, 3));
            return(retval);
        }
예제 #46
0
파일: lab5.cs 프로젝트: mindfulme/cyphers
        static void Main(string[] args)
        {
            var myrsa    = new RSACryptoServiceProvider();
            var encoding = new System.Text.ASCIIEncoding();

            Console.Write("Enter text to encrypt\t");
            var data = Console.ReadLine();

            var newdata   = encoding.GetBytes(data ?? throw new NullReferenceException());
            var encrypted = myrsa.Encrypt(newdata, false);

            Console.Write("Encrypted Data:\t");
            foreach (var t in encrypted)
            {
                Console.Write("{0} ", t);
            }

            var decrypted = myrsa.Decrypt(encrypted, false);

            Console.Write("\n\nDecrypted Data:\t");
            var dData = encoding.GetString(decrypted);

            for (var i = 0; i < decrypted.Length; i++)
            {
                Console.Write("{0}", dData[i]);
            }

            Console.ReadKey();
        }
예제 #47
0
        private String getmixture(int n)
        {
            String s   = "";
            int    cal = 0;

            String[] num = new String[62];

            for (int i = 65; i <= 122; i++)
            {
                if (i > 90 && i < 97)
                {
                    continue;
                }
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                byte[] btNumber = new byte[] { (byte)i };
                num[cal] = asciiEncoding.GetString(btNumber);
                cal     += 1;
            }
            for (int j = 0; j <= 9; j++)
            {
                num[cal] = Convert.ToString(j);
                cal++;
            }
            Random ran = new Random();

            for (int i = 0; i < n; i++)
            {
                int t = ran.Next(num.Length);//产生一个小于num.Length的数字
                s += num[t];
            }
            Session["code"] = s.ToLower();
            return(s);
        }
예제 #48
0
 public string ByteArrayToString(Byte[] bArray)
 {
     string str;
     System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
     str = enc.GetString(bArray);
     return str;
 }
예제 #49
0
파일: ZkdBpSap.cs 프로젝트: Strongc/sencond
 //ASCII 码转字符
 public static string Chr(int asciiCode)
 {
     System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                     byte[] byteArray = new byte[] { (byte)asciiCode };
                     string strCharacter = asciiEncoding.GetString(byteArray);
                     return (strCharacter);
 }
        private string ByteArrayToString(byte[] array)
        {
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            String text = enc.GetString(array).Replace("\0", "");

            return(text);
        }
예제 #51
0
 public string GetCommand()
 {
     System.Text.ASCIIEncoding enc = new ASCIIEncoding();
     byte[] buf = new byte[this.data.Length - 8];
     Array.Copy(this.data, 8, buf, 0, buf.Length);
     return enc.GetString(buf);
 }
예제 #52
0
        private void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream ();

            byte[] message = new byte[4096];
            int bytesRead;

            while (true) {
                bytesRead = 0;

                try {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read (message, 0, 4096);
                }
                catch {
                    //a socket error has occured
                    break;
                }

                if (bytesRead == 0) {
                    //the client has disconnected from the server
                    break;
                }

                //message has successfully been received
                ASCIIEncoding encoder = new ASCIIEncoding ();
                Console.WriteLine (encoder.GetString (message, 0, bytesRead));
                byte[] buffer = encoder.GetBytes("01");
                clientStream.Write(buffer, 0 , buffer.Length);
                clientStream.Flush();
            }

            tcpClient.Close ();
        }
예제 #53
0
        /// <summary>
        /// Decrypts the specified instance byte array.
        /// </summary>
        /// <param name="instanceArray">Instance byte array submitted for decryption.</param>
        /// <returns>Object if decryption was successful; null for otherwise.</returns>
        public static object Decrypt(byte[] instanceArray)
        {
            if (instanceArray == null || instanceArray.LongLength == 0)
            {
                Logger.Warn("Unable to decrypt null or empty byte array!");
                return null;
            }

            if (Logger.IsDebugEnabled)
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                Logger.DebugFormat("Decrypting instance: {0}", encoding.GetString(instanceArray));
            }

            byte[] decryptedInstance;

            try
            {
                decryptedInstance = SimpleEncryption.Decrypt(instanceArray, PassPhrase);
            }
            catch (Exception exception)
            {
                Logger.Error("Problem encountered decrypting the byte array!", exception);
                return null;
            }

            return ObjectUtil.ConvertToObject(decryptedInstance);
        }
예제 #54
0
        private void SocketSend()
        {
            Mess     = "开始读取文本";
            FileLine = null;

            if (!ReadFile(@"C:\Users\yye\Desktop\Recipe.txt") || FileLine == null)
            {
                //MessageBox.Show("数据错误");
                Mess = "数据错误";
                return;
            }
            Mess = "读取文本完成";
            int i = 0;

            sc = new SocketClient("192.168.0.254", 6000);
            while (i < FileLine.Length)
            {
                Mess = "发送:" + i.ToString() + "    \n" + FileLine[i];
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                sc.SendData(FileLine[i] + asciiEncoding.GetString(new byte[] { 13 }));
                while (sc.ReciveData().IndexOf("success") < 0)
                {
                    System.Threading.Thread.Sleep(1);
                }
                i++;
            }
        }
예제 #55
0
        public static string ReadAnsiString(byte[] b, int pos, int length)
        {
            string s;

            System.Text.ASCIIEncoding ansiEncoder = null;
            if (length <= 0)
            {
                return("");
            }
            if (length + pos > b.Length)
            {
                return("");
            }
            ansiEncoder = new System.Text.ASCIIEncoding();
            try
            {
                s = ansiEncoder.GetString(b, pos, length);
                s = s.Replace("\r", " ");
                s = s.Replace("\n", " ");
            }
            catch (Exception)
            {
                return("");
            }
            return(s);
        }
예제 #56
0
 }//private void Write(string message) 
 
 /// <summary></summary>
 private string Response()
 {
  byte [] serverbuff = new Byte[1024]; 
  NetworkStream stream = GetStream(); 
  int count = 0; 
  while (true) 
  {
   byte [] buff = new Byte[2]; 
   int bytes = stream.Read(buff, 0, 1 ); 
   if (bytes == 1) 
   {
    serverbuff[count] = buff[0]; 
    count++; 
    if (buff[0] == '\n') 
    {
     break; 
    } 
   } 
   else 
   {
    break; 
   }; 
  }; 
  string retval = aSCIIEncoding.GetString(serverbuff, 0, count ); 
  Debug.WriteLine(" READ:" + retval); 
  return retval; 
 }//private string Response()
예제 #57
0
        private void OperatorCallBack(IAsyncResult ar)
        {
            try
            {
                int size = sckCommunication.EndReceiveFrom(ar, ref epRemote);

                // check if theres actually information
                if (size > 0)
                {
                    // used to help us on getting the data
                    byte[] aux = new byte[1464];

                    // gets the data
                    aux = (byte[])ar.AsyncState;

                    // converts from data[] to string
                    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                    string msg = enc.GetString(aux);

                    // adds to listbox
                    listBox1.Items.Add("Friend: " + msg);
                }

                // starts to listen again
                buffer = new byte[1464];
                sckCommunication.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None,
                                                  ref epRemote, new AsyncCallback(OperatorCallBack), buffer);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }
예제 #58
0
        public static string Decrypt(this byte[] cipherText, string keyString)
        {
            if (keyString.Length != 32)
            {
                keyString = keyString.GetMD5Hash();
            }
            byte[] IV = new byte[16];   // match slowaes IV

            var ascii = new System.Text.ASCIIEncoding();

            byte[] key = ascii.GetBytes(keyString);

            RijndaelManaged myRijndael = new RijndaelManaged();

            myRijndael.BlockSize = 128;
            myRijndael.KeySize   = 256;
            myRijndael.IV        = IV;
            myRijndael.Padding   = PaddingMode.PKCS7;
            myRijndael.Mode      = CipherMode.CBC;
            myRijndael.Key       = key;

            ICryptoTransform transform = myRijndael.CreateEncryptor();

            // Decrypt the bytes to a string.
            transform = myRijndael.CreateDecryptor();
            byte[] plainText = transform.TransformFinalBlock(cipherText, 0, cipherText.Length);


            return(ascii.GetString(plainText));
        }
예제 #59
0
 public string DecryptString(string valueToDecrypt, byte[] key, byte[] IV)
 {
     ASCIIEncoding encoder = new ASCIIEncoding();
     byte[] value = Convert.FromBase64String(valueToDecrypt);
     byte[] decrypted = DecryptByteArray(value, key, IV);
     return encoder.GetString(decrypted);
 }
예제 #60
0
        public void TC001_FileServerTest()
        {
            string user = Credentials.GenerateCredential();
            string password = Credentials.GenerateCredential();

            string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
            Directory.CreateDirectory(tempPath);

            File.WriteAllText(Path.Combine(tempPath, "test.txt"), "this is a test");

            int port = NetworkInterface.GrabEphemeralPort();

            FileServer fs = new FileServer(port, tempPath, "foobar", user, password);

            fs.Start();

            WebClient client = new WebClient();
            NetworkCredential credentials = new NetworkCredential(user, password);
            client.Credentials = credentials;
            byte[] data = client.DownloadData(String.Format("http://{0}:{1}/foobar/test.txt", "localhost", port));

            ASCIIEncoding encoding = new ASCIIEncoding();
            string retrievedContents = encoding.GetString(data);

            Assert.IsTrue(retrievedContents.Contains("this is a test"));

            //Thread.Sleep(6000000);

            fs.Stop();
        }