Ejemplo n.º 1
0
    static void Main()
    {
        // Reads some text file
        StreamReader read = new StreamReader("file.txt");
        using (read)
        {
            // Creates an empty list and fill it
            string line = read.ReadLine();
            List<string> list = new List<string>();
            for (int l = 0; line != null; l++)
            {
                // Adds each one word from the file in the list
                list.Add(line);

                // Reads the next line
                line = read.ReadLine();
            }

            // Sorting the list
            list.Sort();

            // Write the sorted list in some output file
            StreamWriter write = new StreamWriter("output.txt");
            using (write)
            {
                foreach (var word in list)
                {
                    write.WriteLine(word);
                }
            }
        }
    }
Ejemplo n.º 2
0
    static void Main()
    {
        StreamReader reader = new StreamReader(@"..\..\prologue.txt", Encoding.GetEncoding("windows-1251"));
        using (reader)
        {
            int lineNumber = 1;
            string line = reader.ReadLine();
            while (line != null)
            {
                if (lineNumber % 2 == 1)
                {
                    Console.WriteLine(line);
                    lineNumber++;
                    line = reader.ReadLine();
                }

                else
                {
                    lineNumber++;
                    line = reader.ReadLine();
                }
            }
        }

    }
 private static void ReplaceAllOccurencesOfWholeWorldOnly()
 {
     using (StreamReader input = new StreamReader("text.txt"))
     using (StreamWriter output = new StreamWriter("result.txt"))
         for (string line; (line = input.ReadLine()) != null; )
             output.WriteLine(Regex.Replace(line, @"\bstart\b", "finish"));
 }
Ejemplo n.º 4
0
    public static List<String> GetAllDomainSuffixes()
    {
        if(Helper.allDomainSuffixes == null || Helper.allDomainSuffixes.Count == 0)
        {
            allDomainSuffixes = new List<String>();

            StreamReader reader = new StreamReader(  HttpRuntime.AppDomainAppPath + "/App_Code/DataScience/allDomainSuffixes.txt");

            String line = null;
            while(true)
            {
                line = reader.ReadLine();
                if(line == null){
                    break;
                }

                if(!line.StartsWith("."))
                {
                    continue;
                }

                allDomainSuffixes.Add(line.Split(' ', '\t')[0]);

            }
            reader.Close();
        }
        return allDomainSuffixes;
    }
Ejemplo n.º 5
0
    public static void ReplaceTarget(List<string> words)
    {
        using (StreamReader reader = new StreamReader("test.txt"))
        {
            using (StreamWriter writer = new StreamWriter("temp.txt"))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(@"\b(");
                foreach (string word in words) sb.Append(word + "|");

                sb.Remove(sb.Length - 1, 1);
                sb.Append(@")\b");

                string pattern = @sb.ToString();
                Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);

                for (string line; (line = reader.ReadLine()) != null; )
                {
                    string newLine = rgx.Replace(line, "");
                    writer.WriteLine(newLine);
                }
            }
        }

        File.Delete("test.txt");
        File.Move("temp.txt", "test.txt");
    }
Ejemplo n.º 6
0
 public static Dictionary<string, int> ReplaceFile(string FilePath, string NewFilePath)
 {
     Dictionary<string, int> word_freq = new Dictionary<string, int>();
        using (StreamReader vReader = new StreamReader(FilePath))
        {
       using (StreamWriter vWriter = new StreamWriter(NewFilePath))
       {
          int vLineNumber = 0;
          while (!vReader.EndOfStream)
          {
             string vLine = vReader.ReadLine();
             string[] words = SplitLine(vLine);
             foreach (string s in words) {
                 try {
                     word_freq[s]++;
                     //Console.WriteLine("=> {0}", s);
                 } catch (Exception ex) {
                     word_freq[s] = 1;
                 }
             }
             vWriter.WriteLine(ReplaceLine(vLine, vLineNumber++));
          }
       }
        }
        return word_freq;
 }
Ejemplo n.º 7
0
    static void Main()
    {
        StreamReader text1 = new StreamReader("text1.txt", Encoding.GetEncoding("windows-1251"));
        StreamReader text2 = new StreamReader("text2.txt", Encoding.GetEncoding("windows-1251"));

        using (text1)
        {
            int lineNumber = 1;
            string lineFirstFile = text1.ReadLine();

            Console.WriteLine("The text line are:");
            Console.WriteLine();
            while (lineFirstFile != null)
            {
                string lineSecondFile = text2.ReadLine();

                int result = string.Compare(lineFirstFile, lineSecondFile, true);

                if (result==0)
                {
                    Console.Write("equal at: ");
                    Console.WriteLine(" {0} line ", lineNumber);
                }
                else
                {
                    Console.Write("not equal at:");
                    Console.WriteLine(" {0} line", lineNumber);
                }
                lineNumber++;
                lineFirstFile = text1.ReadLine();
            }

        }
    }
 private static void loadAllExtensionFiles()
 {
     if (extensionFiles == null)
     {
         string[] filePaths;
         extensionFiles = new Dictionary<String, String>();
         try
         {
             filePaths = Directory.GetFiles("Resources/Extensions/", "*.cs");
         }
         catch (DirectoryNotFoundException)
         {
             return;
         } 
         foreach (String fileName in filePaths)
         {
             TextReader tr = new StreamReader(fileName);
             String result = "";
             while (tr.Peek() >= 0)
             {
                 result += tr.ReadLine() + "\n";
             }
             extensionFiles.Add(fileName, result);
             tr.Close();
         }
     }
 }
 static void Main()
 {
     try
     {
         StreamReader reader = new StreamReader(@"D:\newfile.txt");
         List<string> newText = new List<string>();
         using (reader)
         {
             string line = reader.ReadLine();
             int lineNumber = 0;
             while (line != null)
             {
                 lineNumber++;
                 newText.Add(lineNumber.ToString() + ". " + line);
                 line = reader.ReadLine();
             }
         }
         StreamWriter writer = new StreamWriter(File.Open(@"D:\ResultIs.txt",FileMode.Create));
         using (writer)
         {
             for (int i = 0; i < newText.Count; i++)
             {
                 writer.WriteLine(newText[i]);
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
    static void Main()
    {
        StreamReader reader = new StreamReader(@"..\..\input.txt");
        List<string> info = new List<string>();

        using (reader)
        {
            string line = reader.ReadLine();
            while (line != null)
            {
                int i = 0;
                while (i < line.Length - 1)
                {
                    if ((line.IndexOf('>', i) != -1)
                        && (line.IndexOf('>', i) != line.Length - 1)
                        && (line.IndexOf('<', line.IndexOf('>', i)) != line.IndexOf('>', i) + 1))
                    {
                        info.Add(line.Substring(line.IndexOf('>', i) + 1,
                            line.IndexOf('<', line.IndexOf('>', i)) - 1 - line.IndexOf('>', i)));
                        i = line.IndexOf('<', line.IndexOf('>', i)) + 1;
                    }
                    else
                    {
                        i++;
                    }
                }
                line = reader.ReadLine();
            }
        }
        Console.WriteLine(string.Join(",", info));
    }
Ejemplo n.º 11
0
    //Write a program that reads a list of words from a file words.txt and finds how many times 
    //each of the words is contained in another file test.txt. The result should be written in 
    //the file result.txt and the words should be sorted by the number of their occurrences in 
    //descending order. Handle all possible exceptions in your methods.

    private static Dictionary<string, int> CountWords(string inputPath, string listOfWordsPath)
    {
        List<string> list = ExtractList(listOfWordsPath);
        StreamReader reader = new StreamReader(inputPath);
        Dictionary<string, int> result = new Dictionary<string, int>();

        using (reader)
        {
            while (reader.Peek() != -1)
            {
                string currline = reader.ReadLine();

                for (int i = 0; i < list.Count; i++)
                {
                    Regex word = new Regex("\\b" + list[i] + "\\b");

                    foreach (Match match in word.Matches(currline))
                    {
                        //for each word met, if already met - increase counter, else - start counting it
                        if (result.ContainsKey(list[i]))
                        {
                            result[list[i]]++;
                        }
                        else
                        {
                            result.Add(list[i], 1);
                        }
                    }
                }
            }
        }
        return result;
    }
 static void Main()
 {
     using (StreamReader input = new StreamReader("../../1.txt"))
         using (StreamWriter output = new StreamWriter("../../2.txt"))
             for (string line; (line = input.ReadLine()) != null; )
                 output.WriteLine(line.Replace("start", "finish"));
 }
Ejemplo n.º 13
0
    static void Main()
    {
        var reader = new StreamReader("..\\..\\input.txt");
        string[] input = reader.ReadToEnd().Split(' ');
        reader.Close();
        string deletedWord = "start";
        string newWord = "finish";
        for (int i = 0; i < input.Length; i++)
        {
            if (input[i]==deletedWord)
            {
                input[i] = newWord;
            }
        }
        string result = string.Join(" ", input);
        var writer = new StreamWriter("..\\..\\result.txt");
        using (writer)
        {
            if (result != null)
            {
                writer.WriteLine(result);
            }

        }
    }
    static void Main()
    {
        string textOne = "";
        string textTwo = "";
        try
        {
            StreamReader reader = new StreamReader(@"../../FirstTextFile.txt");
            using (reader)
            {
                textOne = reader.ReadToEnd();
            }

            reader = new StreamReader(@"../../SecondTextFile.txt");
            using (reader)
            {
                textTwo = reader.ReadToEnd();
            }

            ConcatenateTwoStrings(textOne, textTwo);
        }
        catch
        {
            Console.WriteLine("Something went wrong! Check file paths or file contents.");
        }
    }
 public static Dictionary<string, int> SameWordsSequences(List<string> words)
 {
     using (StreamReader InputFileTest = new StreamReader("..//..//InputFileTest.txt"))
     {
         Dictionary<string, int> dictionary = new Dictionary<string, int>();
         string line = InputFileTest.ReadLine();
         while (line != null)
         {
             string[] wordsOnLine = line.ToLower().Split(' ', '.', ';', ':');
             foreach (string word in wordsOnLine)
             {
                 if (words.Contains(word))
                 {
                     if (!dictionary.ContainsKey(word))
                     {
                         dictionary.Add(word, 1);
                     }
                     else ++dictionary[word];
                 }
             }
             line = InputFileTest.ReadLine();
         }
         return dictionary;
     }
 }
Ejemplo n.º 16
0
 static void Main()
 {
     StreamReader reader1 = new StreamReader("../../file1.txt");
     StreamReader reader2 = new StreamReader("../../file2.txt");
     string line1 = reader1.ReadLine();
     string line2 = reader2.ReadLine();
     int sameCount = 0;
     int totalCount = 0;
     while (line1 != null) // * Assume the files have equal number of lines.
     {
         if (line1 == line2)
         {
             sameCount++;
         }
         Console.WriteLine("{0} ?= {1} -> {2}", line1, line2, line1 == line2);
         line1 = reader1.ReadLine();
         line2 = reader2.ReadLine();
         totalCount++;
     }
     reader1.Close();
     reader2.Close();
     Console.WriteLine(new string('=', 25));
     Console.WriteLine("Identic lines: {0}", sameCount);
     Console.WriteLine("Different lines: {0}", totalCount - sameCount);
 }
    public string LoadContain()
    {
        if (Request.QueryString["CourseId"] == null)
        {
            return string.Empty;
        }

        string ThePath = string.Empty;
        string RetData = string.Empty;
        using (OleDbConnection Con = new OleDbConnection(constr))
        {
            OleDbCommand cmd = new OleDbCommand(String.Format("SELECT TOP 1 DataPath FROM CoursenotimeDataPath WHERE CourseId = {0}", Request.QueryString["CourseId"]), Con);
            try
            {
                Con.Open();
                ThePath = cmd.ExecuteScalar().ToString();
                //if (ThePath != string.Empty)
                //    ThePath = MapPath(DB.CourseNoTimeFileDir + ThePath);
                ThePath = DB.CourseNoTimeFileDir + ThePath;

                TextReader TR = new StreamReader(ThePath);
                RetData = TR.ReadToEnd();
                TR.Close();
                TR.Dispose();

            }
            catch (Exception ex)
            {
                RetData = ex.Message;
            }
            Con.Close();
        }

        return HttpUtility.HtmlDecode(RetData);
    }
 public object Deserialize(
     StreamReader streamReader, 
     SerializationContext serializationContext, 
     PropertyMetaData propertyMetaData = null)
 {
     return streamReader.ReadInt16();
 }
Ejemplo n.º 19
0
 static void ConcatTwoFiles(string firstFileName, string secondFileName)
 {
     /*Write a program that compares two text files line by line and prints the number of lines that are
       the same and the number of lines that are different. Assume the files have equal number of lines.*/
     int sameLines = 0;
     int differentLines = 0;
     using (StreamReader readFirstFile = new StreamReader(firstFileName))
     {
         using (StreamReader readSecondFile = new StreamReader(secondFileName))
         {
             string lineFirstFile = readFirstFile.ReadLine();
             string lineSecondFile = readSecondFile.ReadLine();
             while (lineFirstFile != null && lineSecondFile != null)
             {
                 if (lineFirstFile == lineSecondFile)
                 {
                     sameLines++;
                 }
                 else
                 {
                     differentLines++;
                 }
                 lineFirstFile = readFirstFile.ReadLine();
                 lineSecondFile = readSecondFile.ReadLine();
             }
         }
     }
     Console.WriteLine("The number of lines that are the same: {0}", sameLines);
     Console.WriteLine("The number of lines that are different: {0}", differentLines);
 }
Ejemplo n.º 20
0
    static void Main()
    {
        StreamReader reader = new StreamReader("../../text.txt", Encoding.GetEncoding("UTF-8"));
        StreamWriter writer = new StreamWriter("../../temp.txt", false, Encoding.GetEncoding("UTF-8"));

        using (reader)
        {
            using (writer)
            {
                string line = reader.ReadLine();

                while (line != null)
                {
                    line = Regex.Replace(line, @"\b(test)\w*\b", "");
                    writer.WriteLine(line);
                    line = reader.ReadLine();
                }
            }
        }

        File.Delete("../../text.txt");
        File.Move("../../temp.txt", "../../text.txt");

        Console.WriteLine("File \"text.txt\" modified!");
    }
    static void Main()
    {
        StreamReader reader = new StreamReader(@"..\..\input.txt");

        List<string> allEvenLines = new List<string>();

        string currLine = null;

        while (1 == 1)
        {
            currLine = reader.ReadLine();//Line1 (1/3/5/7)
            currLine = reader.ReadLine();//Line2 (4/6/8/10)
            if (currLine == null)
            {
                break;
            }
            allEvenLines.Add(currLine);
        }
        reader.Close();

        StreamWriter writer = new StreamWriter(@"..\..\input.txt", false); // after closing the reader
        foreach (string line in allEvenLines)
        {
            writer.WriteLine(line);
        }
        writer.Close();
    }
Ejemplo n.º 22
0
    /*
     * User invoked Event to get device location
     * Invoke AT&T Get Device Location api through http web request along with access token
     * and Disaplys the Device Location of given msisdn
     */
    protected void btnGetDeviceLocation_Click(object sender, EventArgs e)
    {
        try
        {
            string strReq = txtDeviceId.Text;
            string access_tkn = txtAcceTokGetDelStatus.Text.ToString();
            String strResult;

            // Form Http Web Request
            HttpWebResponse objResponse;
            HttpWebRequest objRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://beta-api.att.com/1/devices/tel:"+strReq.ToString()+"/location?access_token="+access_tkn.ToString());

            objRequest.Method = "GET";

            objResponse = (HttpWebResponse)objRequest.GetResponse();
            // the using keyword will automatically dispose the object
            // once complete
            using (StreamReader sr2 = new StreamReader(objResponse.GetResponseStream()))
            {
                strResult = sr2.ReadToEnd();
                Response.Write(strResult.ToString());

                // Close and clean up the StreamReader
                sr2.Close();
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
Ejemplo n.º 23
0
    static void Main()
    {
        StreamReader reader = new StreamReader(@"..\..\practice.txt");
        StringBuilder builder = new StringBuilder();

        using (reader)
        {
            string line = reader.ReadLine();
            int lineIndex = 0;

            while (line != null)
            {
                lineIndex++;
                builder.AppendLine(string.Format("{0}. {1}", lineIndex, line));
                line = reader.ReadLine();
            }
        }

        StreamWriter writer = new StreamWriter(@"..\..\result.txt");

        using (writer)
        {
            writer.Write(builder.ToString());
        }
    }
Ejemplo n.º 24
0
	static string PostStream (Mono.Security.Protocol.Tls.SecurityProtocolType protocol, string url, byte[] buffer)
	{
		Uri uri = new Uri (url);
		string post = "POST " + uri.AbsolutePath + " HTTP/1.0\r\n";
		post += "Content-Type: application/x-www-form-urlencoded\r\n";
		post += "Content-Length: " + (buffer.Length + 5).ToString () + "\r\n";
		post += "Host: " + uri.Host + "\r\n\r\n";
		post += "TEST=";
		byte[] bytes = Encoding.Default.GetBytes (post);

		IPHostEntry host = Dns.Resolve (uri.Host);
		IPAddress ip = host.AddressList [0];
		Socket socket = new Socket (ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
		socket.Connect (new IPEndPoint (ip, uri.Port));
		NetworkStream ns = new NetworkStream (socket, false);
		SslClientStream ssl = new SslClientStream (ns, uri.Host, false, protocol);
		ssl.ServerCertValidationDelegate += new CertificateValidationCallback (CertificateValidation);

		ssl.Write (bytes, 0, bytes.Length);
		ssl.Write (buffer, 0, buffer.Length);
		ssl.Flush ();

		StreamReader reader = new StreamReader (ssl, Encoding.UTF8);
		string result = reader.ReadToEnd ();
		int start = result.IndexOf ("\r\n\r\n") + 4;
		start = result.IndexOf ("\r\n\r\n") + 4;
		return result.Substring (start);
	}
Ejemplo n.º 25
0
    static void Main()
    {
        Console.WriteLine("Enter the full path of the text file");
          string path = Console.ReadLine();
          StreamReader reader = new StreamReader(path);

          StreamWriter writer = new StreamWriter("text.txt", false, Encoding.GetEncoding("windows-1251"));
          List<string> list = new List<string>();

        using (writer)
        {
            using(reader)
            {
                string line = reader.ReadLine();

                    while(line!=null)
                {
                    list.Add(line);
                    line = reader.ReadLine();
                }

                    list.Sort();
            }

            foreach (string s in list)
            {
                writer.WriteLine(s);
            }
        }
    }
Ejemplo n.º 26
0
 static void Main()
 {
     string firstFilePath = @"../../First.txt";
     string secondFilePath = @"../../Second.txt";
     string resultPath = @"../../result.txt";
     StreamReader firstPart = new StreamReader(firstFilePath);
     StreamReader secondPart = new StreamReader(secondFilePath);
     StreamWriter result = new StreamWriter(resultPath);
     string lineOne = String.Empty;
     string lineTwo = String.Empty;
     string resultStr = String.Empty;
     using(firstPart)
     {
         lineOne = firstPart.ReadToEnd();
     }
     using (secondPart)
     {
         lineTwo = secondPart.ReadToEnd();
     }
     using (result)
     {
         resultStr = lineOne + "\r\n" + lineTwo;
         result.WriteLine(resultStr);
     }
 }
Ejemplo n.º 27
0
    static public string Request_POST(string rooturl, string param)
    {

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(rooturl);
        Encoding encoding = Encoding.UTF8;
        byte[] bs = Encoding.ASCII.GetBytes(param);
        string responseData = String.Empty;
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = bs.Length;
        using (Stream reqStream = req.GetRequestStream())
        {
            reqStream.Write(bs, 0, bs.Length);
            reqStream.Close();
        }
        using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
            {
                responseData = reader.ReadToEnd().ToString();
            }
            
        }

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(responseData);
        XmlElement root = doc.DocumentElement;
        return root.InnerText;

    }
Ejemplo n.º 28
0
	// Update is called once per frame
	void Update () {

		// read the cube color from the text file
		// we use fileReadTimer to slow down the read frequency
		if (fileReadTimer++ > 10) {
	        // create reader & open file
	        TextReader tr = new StreamReader("data.txt");
	        // read a line of text
	        ReceivedColor = tr.ReadLine();
	        // close the stream
	        tr.Close();
			
			fileReadTimer = 0;  // reset the timer
		}
	
		// set the Cub color
		switch (ReceivedColor) {
			case "white":
				GetComponent<Renderer>().material.color = Color.white;
				break;
			case "red":
				GetComponent<Renderer>().material.color = Color.red;
				break;
			case "blue":
				GetComponent<Renderer>().material.color = Color.blue;
				break;
			case "green":
				GetComponent<Renderer>().material.color = Color.green;
				break;
			case "yellow":
				GetComponent<Renderer>().material.color = Color.yellow;
				break;
			
		}
	}
 static void Main()
 {
     var readerOne = new StreamReader("test.txt", Encoding.GetEncoding("Windows-1251"));
     var readerTwo = new StreamReader("test2.txt", Encoding.GetEncoding("Windows-1251"));
     using (readerOne)
     {
         int sameCount = 0;
         int differentCount = 0;
         string lineOne = readerOne.ReadLine();
         using (readerTwo)
         {
             string lineTwo = readerTwo.ReadLine();
             while (lineOne != null)
             {
                 if (lineOne == lineTwo)
                 {
                     sameCount++;
                 }
                 else
                 {
                     differentCount++;
                 }
                 lineOne = readerOne.ReadLine();
                 lineTwo = readerTwo.ReadLine();
             }
             Console.WriteLine("The same lines are {0} and the different lines are {1}",sameCount,differentCount);
         }
     }
 }
 static void Main()
 {
     try
     {
         //files are in 'bin/Debug' directory of the project
         string allLines = String.Join(" ", File.ReadAllLines("secondfile.txt"));
         string[] allWords = allLines.Split(' ');
         using (StreamReader start = new StreamReader("mainfile.txt"))
         {
             string line = start.ReadLine();
             using (StreamWriter finish = new StreamWriter("finish.txt"))
             {
                 while (line != null)
                 {
                     for (int i = 0; i < allWords.Length; i++)
                     {
                         string word = "\\b" + allWords[i] + "\\b";
                         line = Regex.Replace(line, word, "");
                     }
                     finish.WriteLine(line);
                     line = start.ReadLine();
                 }
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("{0}:{1}", e.GetType().Name, e.Message);
     }
     Console.WriteLine("Deleting duplicated words was succesful.");
 }
 /* uses badsource and badsink */
 public override void Bad()
 {
     string data;
     if (privateFive == 5)
     {
         data = ""; /* Initialize data */
         {
             try
             {
                 /* read string from file into data */
                 using (StreamReader sr = new StreamReader("data.txt"))
                 {
                     /* POTENTIAL FLAW: Read data from a file */
                     /* This will be reading the first "line" of the file, which
                      * could be very long if there are little or no newlines in the file */
                     data = sr.ReadLine();
                 }
             }
             catch (IOException exceptIO)
             {
                 IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
             }
         }
     }
     else
     {
         /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
          * but ensure data is inititialized before the Sink to avoid compiler errors */
         data = null;
     }
     int p = (int)Environment.OSVersion.Platform;
     string root;
     if (p == (int)PlatformID.Win32NT || p == (int)PlatformID.Win32Windows || p == (int)PlatformID.Win32S || p == (int)PlatformID.WinCE)
     {
         /* running on Windows */
         root = "C:\\uploads\\";
     }
     else
     {
         /* running on non-Windows */
         root = "/home/user/uploads/";
     }
     if (data != null)
     {
         /* POTENTIAL FLAW: no validation of concatenated value */
         if (File.Exists(root + data))
         {
             try
             {
                 using (StreamReader sr = new StreamReader(root + data))
                 {
                     IO.WriteLine(sr.ReadLine());
                 }
             }
             catch (IOException exceptIO)
             {
                 IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
             }
         }
     }
 }
Ejemplo n.º 32
0
        private void IPAddressModifier_Load(object sender, EventArgs e)
        {
            //本地计算机上的网络接口的对象
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in nics)
            {
                adapterListText.Items.Add(adapter.Name);              //list添加节点
                adapterinfo[adapter_i, 0] = adapter.Name;             //适配器名称,数组第一个
                string mac = adapter.GetPhysicalAddress().ToString(); //适配器mac地址
                //格式化mac地址,数组第二个
                try
                {
                    adapterinfo[adapter_i, 1] = mac.Substring(0, 2) + ":" + mac.Substring(2, 2) + ":" + mac.Substring(4, 2) + ":" + mac.Substring(6, 2) + ":" + mac.Substring(8, 2) + ":" + mac.Substring(10, 2);//MAC地址
                }
                catch {
                    adapterinfo[adapter_i, 1] = "00:00:00:00:00:00";
                }
                IPInterfaceProperties ip = adapter.GetIPProperties();     //IP配置信息//获取单播地址集
                UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                foreach (UnicastIPAddressInformation ipadd in ipCollection)
                {
                    if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        adapterinfo[adapter_i, 2] = ipadd.Address.ToString();  //IP地址,数组第三个
                        adapterinfo[adapter_i, 3] = ipadd.IPv4Mask.ToString(); //子网掩码,数组第四个
                    }
                }
                //获取网关,当有多个网关的时候只获取其中一个网关,同时避免了0.0.0.0网关的情况
                //数组第五个
                string ipGateway    = "";
                int    ipGatewayNum = ip.GatewayAddresses.Count;
                if (ip.GatewayAddresses.Count == 0)
                {
                    ipGateway = "0.0.0.0";
                }
                while (--ipGatewayNum >= 0)
                {
                    if (ip.GatewayAddresses[ipGatewayNum].Address.ToString() != "0.0.0.0")
                    {
                        ipGateway = ip.GatewayAddresses[ipGatewayNum].Address.ToString();
                    }
                }
                adapterinfo[adapter_i, 4] = ipGateway;//默认网关
                //获取两个dns信息
                int DnsCount = ip.DnsAddresses.Count;
                //其中第一个为首选DNS,第二个为备用的,余下的所有DNS为DNS备用,按使用顺序排列
                //数组第六个第七个
                for (int i = 0; i < 2; i++)
                {
                    //防止只有一个dns的情况,确保dns占用数组两个位置
                    if (DnsCount == 1 && i == 1)
                    {
                        adapterinfo[adapter_i, 5] = "0.0.0.0";//DNS地址
                    }
                    try
                    {
                        adapterinfo[adapter_i, 4 + i] = ip.DnsAddresses[i].ToString();//DNS地址
                    }
                    catch
                    {
                        adapterinfo[adapter_i, 4 + i] = "0.0.0.0";
                    }
                }
                adapterinfo[adapter_i, 7] = adapter.Id;
                adapter_i++;
            }
            string text = "";

            if (!File.Exists(path))
            {
                FileStream   fs = new FileStream(@path, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                sw.Write("目标IP的名称@MAC地址@IP地址@子网掩码@网关地址@首选DNS地址@备用DNS地址");
                sw.Close();
                fs.Close();
            }
            StreamReader sr = new StreamReader(@path, Encoding.UTF8);

            text = sr.ReadToEnd();
            sr.Close();

            //预设置的自动获取IP地址
            toadapterinfo[0, 0] = "自动获取IP地址";

            toadapterinfo[0, 1] = "00:00:00:00:00:00";
            for (int i = 2; i < 7; i++)
            {
                toadapterinfo[0, i] = "0.0.0.0";
            }
            adapterInfoToText.Items.Add(toadapterinfo[0, 0]);
            //MessageBox.Show(text);//显示全部字符串
            string[] ipAll = text.Split('*');
            //MessageBox.Show(ipAll.Length.ToString());
            for (int i = 0; i < ipAll.Length; i++)
            {
                if (i >= 1)
                {
                    string [] str = ipAll[i].Split('#');
                    for (int j = 0; j < str.Length; j++)
                    {
                        if (j == 0)
                        {
                            str[j] = str[j].Remove(0, 2);
                        }
                        toadapterinfo[i, j] = str[j];
                    }
                    //MessageBox.Show(toadapterinfo[i-1,6].ToString());
                    adapterInfoToText.Items.Add(toadapterinfo[i, 0]);
                }
            }
            adapterListText.SelectedIndex   = 0;
            adapterInfoToText.SelectedIndex = 0;

            //设置label中的值的字体居中
            adapterNameText.TextAlign    = System.Drawing.ContentAlignment.MiddleCenter;
            adapterMacText.TextAlign     = System.Drawing.ContentAlignment.MiddleCenter;
            adapterIPText.TextAlign      = System.Drawing.ContentAlignment.MiddleCenter;
            adapterSubText.TextAlign     = System.Drawing.ContentAlignment.MiddleCenter;
            adapterGatewayText.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            adapterDNS1Text.TextAlign    = System.Drawing.ContentAlignment.MiddleCenter;
            adapterDNS2Text.TextAlign    = System.Drawing.ContentAlignment.MiddleCenter;

            //设置label中的键的字体居中
            adapterName.TextAlign    = System.Drawing.ContentAlignment.MiddleCenter;
            adapterMac.TextAlign     = System.Drawing.ContentAlignment.MiddleCenter;
            adapterIP.TextAlign      = System.Drawing.ContentAlignment.MiddleCenter;
            adapterSub.TextAlign     = System.Drawing.ContentAlignment.MiddleCenter;
            adapterGateway.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            adapterDNS1.TextAlign    = System.Drawing.ContentAlignment.MiddleCenter;
            adapterDNS2.TextAlign    = System.Drawing.ContentAlignment.MiddleCenter;
        }
Ejemplo n.º 33
0
 public static CsvReader CreateCsvReader(StreamReader streamReader)
 {
     return(new CsvReader(streamReader, CultureInfo.InvariantCulture));
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CsvLight"/> class.
 /// </summary>
 /// <param name="reader">Input Stream Reader.</param>
 /// <param name="delimiter">Fields Delimiter.</param>
 public CsvLight(StreamReader reader, char delimiter)
 {
     this.Initialize(reader, delimiter, true, true);
 }
Ejemplo n.º 35
0
        static void ServerWorker(Object obj)
        {
            TcpClient cli = (TcpClient)obj;

            try
            {
                StreamReader reader     = new StreamReader(cli.GetStream());
                StreamWriter writer     = new StreamWriter(cli.GetStream());
                String       clientInfo = reader.ReadLine(); // citanje info za najaveniot klient
                Console.WriteLine(clientInfo);
                int             clid = Convert.ToInt32(clientInfo.Split(',')[0]);
                String          pw   = clientInfo.Split(',')[1];
                int             port = ((IPEndPoint)cli.Client.RemoteEndPoint).Port;
                ClientContainer cc   = new ClientContainer(clid, pw, cli.GetStream(), writer);
                if (!listOfClients.Contains(cc))
                {
                    writer.WriteLine("Најавата е успешна.");
                    writer.Flush();
                    listOfClients.AddLast(cc);
                    Console.WriteLine("Успешно додаден клиент во листата.");
                    while (true)
                    {
                        String poraka;
                        while ((poraka = reader.ReadLine()) == null)
                        {
                            ;
                        }
                        int toId = Convert.ToInt32(poraka);
                        if (IdExists(toId))
                        {
                            Console.WriteLine("Проверка ID");
                            writer.WriteLine("ПОСТОИ");
                            writer.Flush();
                            String          toPwd = reader.ReadLine();
                            ClientContainer ccon;
                            if ((ccon = PasswordAuthentication(toId, toPwd)) != null)
                            {
                                Console.WriteLine("Проверка Password");
                                writer.WriteLine("ТОЧЕН");
                                writer.Flush();
                                String row;
                                row = reader.ReadLine();
                                String [] buffer = new String[100];
                                buffer[0] = row;
                                int i = 1;
                                Console.WriteLine(buffer[0]);
                                while (!(row = reader.ReadLine()).Equals("END"))
                                {
                                    buffer[i] = row;
                                    //Console.WriteLine(buffer[i]);
                                    i++;
                                    //Console.WriteLine(i);
                                }
                                Console.WriteLine("#Пренесувам датотека " + buffer[0]);
                                StreamWriter writerTo = ccon.getWriter();
                                writerTo.WriteLine(buffer[0]);
                                writerTo.Flush();
                                i = 1;
                                while (i < 100)
                                {
                                    writerTo.WriteLine(buffer[i]);
                                    i++;
                                }
                                writerTo.WriteLine("END");
                                writerTo.Flush();
                                Console.WriteLine("Завршено пренесување");
                            }
                            else
                            {
                                writer.WriteLine("ГРЕШЕН");
                                writer.Flush();
                            }
                        }
                        else
                        {
                            writer.WriteLine("НЕПОСТОИ");
                            writer.Flush();
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Додавањето во листа е неуспешно.");
                    writer.WriteLine("Најавата е неуспешна.");
                    writer.Flush();
                }
            }
            catch
            {
            }
            finally
            {
                if (cli != null)
                {
                    cli.Close();
                }
            }
        }
Ejemplo n.º 36
0
        private string partialField;  // when field we are building is split across buffers

        /// <summary>
        /// Initializes a new instance of the <see cref="CsvLight"/> class.
        /// </summary>
        /// <param name="reader">Input Stream Reader.</param>
        public CsvLight(StreamReader reader)
        {
            this.Initialize(reader, ',', true, true);
        }
Ejemplo n.º 37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CsvLight"/> class.
 /// </summary>
 /// <param name="reader">Input Stream Reader.</param>
 /// <param name="delimiter">Fields Delimiter.</param>
 /// <param name="trim">Whether to trim spaces.</param>
 /// <param name="headers">Whether has headers.</param>
 public CsvLight(StreamReader reader, char delimiter, bool trim, bool headers)
 {
     this.Initialize(reader, delimiter, trim, headers);
 }