Beispiel #1
0
 private void RecordStop(string filename)
 {
     mciSendString("save recsound " + filename, "", 0, 0);
     mciSendString("close recsound ", "", 0, 0); 
     Computer c = new Computer(); 
     c.Audio.Stop();
 }
        private static void Main()
        {
            // Using :: with aliases is a good idea and protects against the unexpected introduction of additional types.
            var dataColumn = new data::DataColumn();
            var dataColumn2 = new data.DataColumn();

            con.WriteLine("Can access type through . notation");
            //con::WriteLine("Cannot access type through :: notation");

            const int Console = 1;
            // The ability to access a member in the global namespace is useful when the member might be hidden by another
            // entity of the same name.
            //System.Console.WriteLine(Console); does not compile
            global::System.Console.WriteLine(Console);

            // Using Microsoft.VisualBasic.MyServices
            // Display machine information with the Computer class:
            var myComputer = new Computer();
            global::System.Console.WriteLine("Computer name: " + myComputer.Name);

            global::System.Console.WriteLine(myComputer.Network.IsAvailable
                                                 ? "Computer is connected to network."
                                                 : "Computer is not connected to network.");

            // Display time information with the Clock class:
            var myClock = new Clock();
            global::System.Console.Write("Current day of the week: ");
            global::System.Console.WriteLine(myClock.LocalTime.DayOfWeek);
            global::System.Console.Write("Current date and time: ");
            global::System.Console.WriteLine(myClock.LocalTime);
        }
 public void SendMicrophoneCapture(byte[] capture)
 {
     lock (_sync)
     {
         Computer computer = new Computer();
         computer.Audio.Play(capture, AudioPlayMode.Background);
     }
 }
Beispiel #4
0
 public void RenameFile(string p_strFileDir)
 {
     richTextBox1.Text = "";
     foreach (FileInfo item in fiarray)
     {
         Computer c = new Computer();
         string s = Guid.NewGuid().ToString();
         c.FileSystem.RenameFile(item.FullName, s+"."+item.Extension);
         richTextBox1.Text += s + "." + item.Extension + "\n";
     }
 }
Beispiel #5
0
 public string GetMyMemoryInfo()
 {//获取当前计算机的内存信息
     try
     {
         Microsoft.VisualBasic.Devices.Computer My = new Microsoft.VisualBasic.Devices.Computer();
         return((My.Info.AvailablePhysicalMemory / 1024 / 1024).ToString() + "M/" + (My.Info.TotalPhysicalMemory / 1024 / 1024).ToString() + "M");
     }
     catch
     {
         return("");
     }
 }
Beispiel #6
0
        public Form1()
        {
            InitializeComponent();

            this.StartPosition = FormStartPosition.CenterScreen;
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;

            this.cmp = new Computer();

            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                this.cpuCounters.Add(new PerformanceCounter("Processor", "% Processor Time", i.ToString()));
                NotifyIcon nic = new NotifyIcon() { Icon = SystemIcons.Question, Visible = true };
                nic.Click += RightClick;
                this.cpuNotifyIcons.Add(nic);
            }

            this.ramIcon = new NotifyIcon() { Icon = SystemIcons.Question, Visible = true };
            this.ramIcon.Click += RightClick;

            this.timer1.Interval = 250;
            this.timer1.Start();
        }
Beispiel #7
0
		public static MemoryInformation GetMemoryInformation()
		{
			var returnVal = new MemoryInformation();

#if !__MonoCS__ // There are completely different dependencies and code per platform for finding the memory information
			var computerInfo = new Computer().Info;
			returnVal.TotalPhysicalMemory = computerInfo.TotalPhysicalMemory;
			returnVal.TotalVirtualMemory = computerInfo.TotalVirtualMemory;
#else
			var meminfo = File.ReadAllText("/proc/meminfo");
			var match = new Regex(@"MemTotal:\s+(\d+) kB").Match(meminfo);
			if (match.Success)
				returnVal.TotalPhysicalMemory = ulong.Parse(match.Groups[1].Value) * 1024;
			ulong totalSwapMemory = 0;
			var match2 = new Regex(@"SwapTotal:\s+(\d+) kB").Match(meminfo);
			if (match2.Success)
				totalSwapMemory = ulong.Parse(match2.Groups [1].Value) * 1024;
			var availableMemory = returnVal.TotalPhysicalMemory + totalSwapMemory;
			var is64BitProcess = IntPtr.Size == 8; // according to MSDN
			if (is64BitProcess)
			{
				returnVal.TotalVirtualMemory = availableMemory;
			}
			else
			{
				// Googling indicates that 32-bit Mono programs attempting to allocate more than
				// about 1.4 GB start running into OutOfMemory errors.  So 2GB is probably the
				// right virtual memory limit for 32-bit processes.
				const ulong twoGB = 2147483648L;
				returnVal.TotalVirtualMemory = availableMemory > twoGB ? twoGB : availableMemory;
			}
#endif
			return returnVal;
		}
		/// <summary>
		/// Write to the logger a message containing the event string, the total memory this process is using,
		/// its working set (real memory), .NET heap memory, and the total physical and virtual memory on the system
		/// If botherUser is true and total memory in use is more than 1G, it will display a dialog saying
		/// "This program is using a lot of memory, and may soon slow down or experience other problems.
		/// We recommend that you quit and restart it when convenient." This will happen only once per session.
		/// Enhance: (Do we need a way to turn it off altogether? Should we have an argument whereby the threshold can be controlled?)
		/// </summary>
		/// <param name="minor">True to write a minor event, false to write full event</param>
		/// <param name="eventDescription"></param>
		/// <param name="okToBotherUser">The first time it is called with this true and short of memory, display a dialog.</param>
		/// <returns>true if total memory in use is more than 1G (whether or not we bothered the user)</returns>
		public static bool CheckMemory(bool minor, string eventDescription, bool okToBotherUser)
		{
			// the best available approximation of the number of bytes currently allocated in managed memory.
			var heapMem = GC.GetTotalMemory(true); // first, as it may reduce other numbers
			var is64BitProcess = IntPtr.Size == 8; // according to MSDN
			long memorySize64;
			long workingSet64;
			string message;
			ulong totalPhysicalMemory = 0;
			string totalVirtualMemory = "unknown";

#if !__MonoCS__ // There are completely different dependencies and code per platform for finding the memory information
				var computerInfo = new Computer().Info;
				totalPhysicalMemory = computerInfo.TotalPhysicalMemory;
				totalVirtualMemory = (computerInfo.TotalVirtualMemory / 1024).ToString("N0");
#else
				var meminfo = File.ReadAllText("/proc/meminfo");
				var match = new Regex(@"MemTotal:\s+(\d+) kB").Match(meminfo);
				if (match.Success)
					totalPhysicalMemory = ulong.Parse(match.Groups[1].Value) * 1024;
				ulong totalSwapMemory = 0;
				var match2 = new Regex(@"SwapTotal:\s+(\d+) kB").Match(meminfo);
				if (match2.Success)
					totalSwapMemory = ulong.Parse(match2.Groups [1].Value) * 1024;
				var availableMemory = totalPhysicalMemory + totalSwapMemory;
				if (is64BitProcess)
				{
					totalVirtualMemory = (availableMemory / 1024).ToString ("N0");
				}
				else
				{
					// Googling indicates that 32-bit Mono programs attempting to allocate more than
					// about 1.4 GB start running into OutOfMemory errors.  So 2GB is probably the
					// right virtual memory limit for 32-bit processes.
					ulong twoGB = 2147483648L;
					totalVirtualMemory = ((availableMemory > twoGB ? twoGB : availableMemory) / 1024).ToString("N0");
				}
#endif
			using (var proc = Process.GetCurrentProcess())
			{
				// the current size of the process memory that cannot be shared with other processes.
				memorySize64 = proc.PrivateMemorySize64;
				// the current size of the process memory currently in physical RAM memory.
				workingSet64 = proc.WorkingSet64;
				// the current size of all memory used by the process, split between pages loaded in physical memory and pages stored on disk.
				long virtualMemory64 = proc.VirtualMemorySize64;
				// the maximum amount of physical memory allocated for the process since it was started.
				long peakWorkingSet64 = proc.PeakWorkingSet64;
				// the maximum amount of virtual memory allocated for the process since it was started.
				long peakVirtualMemory64 = proc.PeakVirtualMemorySize64;
				StringBuilder bldr = new StringBuilder();
				bldr.AppendFormat("{0}:", eventDescription);
				bldr.AppendFormat(" Memory Use ({0}-bit process): private {1:N0}K, virtual {2:N0}K,", is64BitProcess ? 64 : 32, memorySize64/1024, virtualMemory64/1024);
				bldr.AppendFormat(" physical {0:N0}K,", workingSet64/1024);
				bldr.AppendFormat(" managed heap {0:N0}K,", heapMem/1024);
				bldr.AppendLine();
				bldr.AppendFormat("        peak virtual {0:N0}K, peak physical {1:N0}K;", peakVirtualMemory64/1024, peakWorkingSet64/1024);
				bldr.AppendFormat(" system virtual {0}K, system physical (RAM) {1:N0}K", totalVirtualMemory, totalPhysicalMemory/1024);
				bldr.AppendLine();
				message = bldr.ToString();
			}
			if (minor)
				Logger.WriteMinorEvent(message);
			else
				Logger.WriteEvent(message);
			Debug.Write("DEBUG: " + message);
			// Limit memory below 1GB unless we have a 64-bit process with lots of physical memory.
			// In that case, still limit memory to well under 2GB before warning.
			long safelimit = 1000000000;
			if (is64BitProcess && totalPhysicalMemory >= 8192000000L)
				safelimit = 2000000000;
			bool danger = false;
			// In Windows/.Net, Process.PrivateMemorySize64 seems to give a reasonable value for current
			// memory usage.  In Linux/Mono, Process.PrivateMemorySize64 seems to include a large amount
			// of virtual memory.  In that context, Process.WorkingSet64 appears to be the best bet for
			// approximating how much memory the process is currently using.  (It may be that this would
			// be a better value for Windows as well, but we'll leave it as it is for now.)
			if (Platform.IsWindows)
				danger = memorySize64 > safelimit;
			else
				danger = workingSet64 > safelimit;
			if (danger && okToBotherUser && !s_warningShown)
			{
				s_warningShown = true;
				var warning = LocalizationManager.GetString("MemoryWarning",
					"Unfortunately, {0} is starting to get short of memory, and may soon slow down or experience other problems. We recommend that you quit and restart it when convenient.");
				var caption = LocalizationManager.GetString("Warning", "Warning");
				MessageBox.Show(null, string.Format(warning, Application.ProductName), caption, MessageBoxButtons.OK,
					MessageBoxIcon.Warning);
			}
			return danger;
		}
Beispiel #9
0
        private void ProcessList()
        {
            Computer comp = new Computer();
            int copied = 0;

            Status = PlayListItemStatus.Proccessing;
            foreach (ClipItem clip in ClipList)
            {
                try
                {
                    string dest = general.getDestinationFile(clip.VideoFile);

                    if (dest == "")
                    {
                        NoDestinationFiles.Add(clip.VideoFile);
                        ProceedFiles++;
                        continue;
                    }

                    string dir = Path.GetDirectoryName(dest);
                    if (!Directory.Exists(dir))
                    {
                            Directory.CreateDirectory(dir);

                    }

                    if (!File.Exists(dest))
                    {
                        if (!NoLocaling)
                        {

                            comp.FileSystem.CopyFile(clip.VideoFile, dest, UIOption.AllDialogs, UICancelOption.ThrowException);
                            copied++;
                        }
                        else
                        {
                            ProceedFiles++;
                            continue;
                        }
                    }
                    else
                    {
                        if (Settings.PathDateModified(dest))
                        {
                            FileInfo srcfi = new FileInfo(clip.VideoFile);
                            FileInfo dstfi = new FileInfo(dest);

                            if (dstfi.LastWriteTime < srcfi.LastWriteTime || srcfi.Length != dstfi.Length)
                            {
                                if (general.DeleteFile(dest))
                                {
                                    comp.FileSystem.CopyFile(clip.VideoFile, dest, UIOption.AllDialogs, UICancelOption.ThrowException);
                                    copied++;
                                }
                            }
                        }
                    }

                    ProceedFiles++;
                    Content = Content.Replace(clip.VideoFile, dest);

                }
                catch (Exception ex)
                {
                    Status = PlayListItemStatus.Error;
                    MessageBox.Show("Error (File Copy) : " + ex.Message, "File Copy...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            if (Status != PlayListItemStatus.Error)
            {
                Status = PlayListItemStatus.Complete;

                try
                {
                    string dest = general.getDestinationFile(ListFilePath);

                    string dir = Path.GetDirectoryName(dest);
                    if (!Directory.Exists(dir))
                        Directory.CreateDirectory(dir);

                    if (File.Exists(dest) && copied == 0)
                    {
                        return;
                    }

                    File.WriteAllText(dest, Content, Encoding.Default);
                }
                catch (Exception ex)
                {
                    Status = PlayListItemStatus.Error;
                    MessageBox.Show("Error (List File Copy) : " + ex.Message, "List File Copy...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #10
0
        public void getInfo1(ListView lv)
        {
            info[0] = "����ϵͳ";
            info[1]=Environment.OSVersion.VersionString;
            ListViewItem item = new ListViewItem(info, "����ϵͳ");
            lv.Items.Add(item);

            RegistryKey mykey = Registry.LocalMachine;
            mykey = mykey.CreateSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion");
            string a = (string)mykey.GetValue("RegisteredOrganization");
            mykey.Close();
            info[0] = "ע���û�";
            info[1] = a;
            ListViewItem item1 = new ListViewItem(info, "ע���û�");
            lv.Items.Add(item1);

            info[0] = "Windows�ļ���";
            info[1] = Environment.GetEnvironmentVariable("WinDir");
            ListViewItem item2 = new ListViewItem(info, "Windows�ļ���");
            lv.Items.Add(item2);

            info[0] = "ϵͳ�ļ���";
            info[1] = Environment.SystemDirectory.ToString();
            ListViewItem item3= new ListViewItem(info, "ϵͳ�ļ���");
            lv.Items.Add(item3);

            info[0] = "���������";
            info[1] = Environment.MachineName.ToString();
            ListViewItem item4 = new ListViewItem(info, "���������");
            lv.Items.Add(item4);

            info[0] = "��������ʱ��";
            info[1] = DateTime.Now.ToString();
            ListViewItem item5 = new ListViewItem(info, "��������ʱ��");
            lv.Items.Add(item5);

            string MyInfo = "";
            ManagementObjectSearcher MySearcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
            foreach (ManagementObject MyObject in MySearcher.Get())
            {
                MyInfo += MyObject["InstallDate"].ToString().Substring(0, 8);
            }
            MyInfo = MyInfo.Insert(4, "-");
            MyInfo = MyInfo.Insert(7,"-");
            info[0] = "ϵͳ��װ����";
            info[1] = MyInfo;
            ListViewItem item6 = new ListViewItem(info, "ϵͳ��װ����");
            lv.Items.Add(item6);

            String MyInfo1 = "";
            ManagementObjectSearcher MySearcher1 = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
            foreach (ManagementObject MyObject in MySearcher1.Get())
            {
                MyInfo1 += MyObject["LastBootUpTime"].ToString().Substring(0, 8);
            }
            MyInfo1 = MyInfo1.Insert(4, "-");
            MyInfo1 = MyInfo1.Insert(7, "-");
            info[0] = "ϵͳ���ʱ��";
            info[1] = MyInfo1;
            ListViewItem item7 = new ListViewItem(info, "ϵͳ���ʱ��");
            lv.Items.Add(item7);

            Microsoft.VisualBasic.Devices.Computer My = new Microsoft.VisualBasic.Devices.Computer();
            info[0]="�����ڴ�����(M)";
            info[1] = (My.Info.TotalPhysicalMemory / 1024 / 1024).ToString();
            ListViewItem item8 = new ListViewItem(info, "�����ڴ�����(M)");
            lv.Items.Add(item8);

            info[0] = "�����ڴ�����(M)";
            info[1] = (My.Info.TotalVirtualMemory / 1024 / 1024).ToString();
            ListViewItem item9 = new ListViewItem(info, "�����ڴ�����(M)");
            lv.Items.Add(item9);

            info[0] = "���������ڴ�����(M)";
            info[1] =(My.Info.AvailablePhysicalMemory / 1024 / 1024).ToString();
            ListViewItem item10 = new ListViewItem(info, "���������ڴ�����(M)");
            lv.Items.Add(item10);

            info[0] = "���������ڴ�����(M)";
            info[1] = (My.Info.AvailableVirtualMemory / 1024 / 1024).ToString();
            ListViewItem item11 = new ListViewItem(info, "���������ڴ�����(M)");
            lv.Items.Add(item11);

            info[0] = "ϵͳ������";
            info[1] = Environment.GetEnvironmentVariable("SystemDrive");
            ListViewItem item12 = new ListViewItem(info, "ϵͳ������");
            lv.Items.Add(item12);

            info[0] = "����Ŀ¼";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            ListViewItem item13 = new ListViewItem(info, "ϵͳ������");
            lv.Items.Add(item13);

            info[0] = "�û�������Ŀ¼";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
            ListViewItem item14 = new ListViewItem(info, "�û�������Ŀ¼");
            lv.Items.Add(item14);

            info[0] = "�ղؼ�Ŀ¼";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
            ListViewItem item15 = new ListViewItem(info, "�ղؼ�Ŀ¼");
            lv.Items.Add(item15);

            info[0] = "Internet��ʷ��¼";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.History);
            ListViewItem item16 = new ListViewItem(info, "Internet��ʷ��¼");
            lv.Items.Add(item16);

            info[0] = "Internet��ʱ�ļ�";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
            ListViewItem item17 = new ListViewItem(info, "Internet��ʱ�ļ�");
            lv.Items.Add(item17);
        }
 /// <summary>
 /// Sets all current accounts as not for upload, so the new account can be the upload account
 /// </summary>
 internal static void SetOtherAccountsAsNotForUpload()
 {
     try
     {
         AWBProfiles.ResetTempPassword();
         foreach (int id in GetProfileIDs())
         {
             Microsoft.Win32.RegistryKey key = new Computer().Registry.CurrentUser.OpenSubKey(RegKey + "\\" + id, true);
             key.SetValue("UseForUpload", false);
         }
     }
     catch { }
 }
Beispiel #12
0
 public void StopRecording()
 {
     Win32APIMethods.mciSendString("close recsound ", "", 0, 0);
     Computer c = new Computer();
     c.Audio.Stop();
     File.Delete("c:\\record.wav");
     _audioStreamRunning = false;
 }
Beispiel #13
0
 private void PlaySound(string fileToPlay)
 {
     var myComputer = new Computer();
     myComputer.Audio.Play(@fileToPlay);
 }
Beispiel #14
0
 public static string getPCName()
 {
     Computer pc = new Computer();
     return pc.Name.ToString();
 }
Beispiel #15
0
 private static void MessageSound()
 {
     Computer myComputer = new Computer();
     myComputer.Audio.Play(@"c:\WINDOWS\Media\chimes.wav");
 }
 /// <summary>
 /// Sets the Profile Password in the Registry
 /// </summary>
 /// <param name="id">Profile ID</param>
 /// <param name="password">Password</param>
 private static void SetProfilePassword(int id, string password)
 {
     try
     {
         Microsoft.Win32.RegistryKey key = new Computer().Registry.CurrentUser.OpenSubKey(RegKey + "\\" + id, true);
         key.SetValue("Pass", password);
     }
     catch { }
 }
Beispiel #17
0
 private void Form1_Load(object sender, EventArgs e)
 {
     Computer MyComputer = new Computer();
     txtResult.Text = MyComputer.FileSystem.ReadAllText("test.txt");
 }
 static void ShowStatus(List<string> args)
 {
     Computer com = new Computer();
     bool isFirst = true;
     bool isZero = true;
     foreach (string str in com.Ports.SerialPortNames)
     {
         if (isFirst)
         {
             Console.WriteLine("系统可用的串口有:");
             isFirst = false;
             isZero = false;
         }
         Console.WriteLine(str);
     }
     if (isZero)
     {
         Console.WriteLine("系统没有可用的串口");
     }
     if(serialPort.IsOpen)
         Console.WriteLine("当前串口处于打开状态:");
     else
         Console.WriteLine("当前串口处于关闭状态:");
     Console.WriteLine("串口名称:   " + serialPort.PortName);
     Console.WriteLine("波特率:     " + serialPort.BaudRate);
     Console.WriteLine("奇偶校验位: " + serialPort.Parity);
     Console.WriteLine("数据位:     " + serialPort.DataBits);
     Console.WriteLine("停止位:     " + serialPort.StopBits);
 }
Beispiel #19
0
        public static void MyCopyAllFilesInFolder(Task buildTask, string sourceFolder, string targetFolder, string wildCards, bool overWrite, bool onlyReplaceWithNewerFile, bool continueOnError, Microsoft.VisualBasic.FileIO.SearchOption searchOption, bool useRoboCopy, string versionToCopy, string logText)
        {
            var myComputer = new Computer();
            RobocopyWrapper myWrapper = null;
            if (useRoboCopy)
            {
                myWrapper = new RobocopyWrapper();
                useRoboCopy = myWrapper.IsInstalled;
                if (useRoboCopy)
                {
                    if (myWrapper.SupportsMultiThreading)
                    {
                        myWrapper.NumberOfThreads = 8;
                    }
                    else
                    {
                        myWrapper.NumberOfThreads = 1;
                    }
                    switch (searchOption)
                    {
                        case Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly:
                            myWrapper.RecursiveMode = RoboCopyRecursiveCopy.CopyTopLevelOnly;
                            break;

                        case Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories:
                            myWrapper.RecursiveMode = RoboCopyRecursiveCopy.CopyAllSubdirectories;
                            break;
                    }
                }
            }
            if (Strings.Len(wildCards) == 0)
            {
                wildCards = "*.*";
            }
            if (Strings.Len(logText) == 0)
            {
                logText = "Copying folder from '{0}' to '{1}'...";
            }
            if (Directory.Exists(sourceFolder))
            {
                MyLogMessage(buildTask, string.Format(logText, sourceFolder, targetFolder), MessageImportance.Normal);
                if (useRoboCopy)
                {
                    MyCopyAllFilesWithRoboCopy(buildTask, myWrapper, sourceFolder, targetFolder, wildCards, onlyReplaceWithNewerFile, continueOnError, versionToCopy);
                }
                else
                {
                    //foreach (string str2 in _MyComputer.FileSystem.GetFiles()
                    foreach (string str2 in myComputer.FileSystem.GetFiles(sourceFolder, searchOption, new string[] { wildCards }))
                    {
                        string targetFile = "";
                        try
                        {
                            string fullPath = Path.GetFullPath(sourceFolder);
                            targetFile = PathHelper.Combine(targetFolder, Strings.Right(str2, (str2.Length - fullPath.Length) - 1));
                            MyCopyFile(buildTask, str2, targetFile, overWrite, onlyReplaceWithNewerFile, "Copying file from '{0}' to '{1}'...", false);
                        }
                        catch (Exception exception1)
                        {
                            ProjectData.SetProjectError(exception1);
                            Exception ex = exception1;
                            if (!continueOnError)
                            {
                                throw;
                            }
                            string exceptionData = GetExceptionData(ex);
                            MyLogWarning(buildTask, string.Format("Error copying file '{0}' to '{1}'. The following error was raised: '{2}'.", str2, targetFile, exceptionData));
                            ProjectData.ClearProjectError();
                        }
                    }
                }
            }
            else
            {
                MyLogMessage(buildTask, string.Format("Source folder '{0}' does not exist and cannot be copied to '{1}'.", sourceFolder, targetFolder), MessageImportance.Normal);
            }
        }
        /// <summary>
        /// Gets a Specified Profile from the Registry
        /// </summary>
        /// <param name="id">Profile ID to get</param>
        /// <returns>Specified Profile</returns>
        public static AWBProfile GetProfile(int id)
        {
            AWBProfile prof = new AWBProfile();
            Computer myComputer = new Computer();

            prof.id = id;
            try { prof.Username = Decrypt(myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "User", "").ToString()); }
            catch
            {
                if (MessageBox.Show("Profile corrupt. Would you like to delete this profile?", "Delete corrupt profile?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    DeleteProfile(id);

                throw new Exception("");
            }

            // one try...catch without a resume has the effect that all remaining code in the try block is skipped
            // WHY are we just ignoring these errors anyway? There should be a wrapper around Registry.GetValue perhaps?
            try { prof.Password = Decrypt(myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "Pass", "").ToString()); }
            catch { prof.Password = ""; }
            finally
            {
                prof.defaultsettings = myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "Settings", "").ToString();
                try { prof.useforupload = bool.Parse(myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "UseForUpload", "").ToString()); }
                catch { prof.useforupload = false; }
                prof.notes = myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "Notes", "").ToString();
            }
            return prof;
        }
Beispiel #21
0
        public void getInfo1(ListView lv)
        {
            info[0] = "操作系统";
            info[1] = Environment.OSVersion.VersionString;
            ListViewItem item = new ListViewItem(info, "操作系统");

            lv.Items.Add(item);

            RegistryKey mykey = Registry.LocalMachine;

            mykey = mykey.CreateSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion");
            string a = (string)mykey.GetValue("RegisteredOrganization");

            mykey.Close();
            info[0] = "注册用户";
            info[1] = a;
            ListViewItem item1 = new ListViewItem(info, "注册用户");

            lv.Items.Add(item1);

            info[0] = "Windows文件夹";
            info[1] = Environment.GetEnvironmentVariable("WinDir");
            ListViewItem item2 = new ListViewItem(info, "Windows文件夹");

            lv.Items.Add(item2);

            info[0] = "系统文件夹";
            info[1] = Environment.SystemDirectory.ToString();
            ListViewItem item3 = new ListViewItem(info, "系统文件夹");

            lv.Items.Add(item3);

            info[0] = "计算机名称";
            info[1] = Environment.MachineName.ToString();
            ListViewItem item4 = new ListViewItem(info, "计算机名称");

            lv.Items.Add(item4);

            info[0] = "本地日期时间";
            info[1] = DateTime.Now.ToString();
            ListViewItem item5 = new ListViewItem(info, "本地日期时间");

            lv.Items.Add(item5);

            string MyInfo = "";
            ManagementObjectSearcher MySearcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");

            foreach (ManagementObject MyObject in MySearcher.Get())
            {
                MyInfo += MyObject["InstallDate"].ToString().Substring(0, 8);
            }
            MyInfo  = MyInfo.Insert(4, "-");
            MyInfo  = MyInfo.Insert(7, "-");
            info[0] = "系统安装日期";
            info[1] = MyInfo;
            ListViewItem item6 = new ListViewItem(info, "系统安装日期");

            lv.Items.Add(item6);


            String MyInfo1 = "";
            ManagementObjectSearcher MySearcher1 = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");

            foreach (ManagementObject MyObject in MySearcher1.Get())
            {
                MyInfo1 += MyObject["LastBootUpTime"].ToString().Substring(0, 8);
            }
            MyInfo1 = MyInfo1.Insert(4, "-");
            MyInfo1 = MyInfo1.Insert(7, "-");
            info[0] = "系统启动时间";
            info[1] = MyInfo1;
            ListViewItem item7 = new ListViewItem(info, "系统启动时间");

            lv.Items.Add(item7);

            Microsoft.VisualBasic.Devices.Computer My = new Microsoft.VisualBasic.Devices.Computer();
            info[0] = "物理内存总量(M)";
            info[1] = (My.Info.TotalPhysicalMemory / 1024 / 1024).ToString();
            ListViewItem item8 = new ListViewItem(info, "物理内存总量(M)");

            lv.Items.Add(item8);

            info[0] = "虚拟内存总量(M)";
            info[1] = (My.Info.TotalVirtualMemory / 1024 / 1024).ToString();
            ListViewItem item9 = new ListViewItem(info, "虚拟内存总量(M)");

            lv.Items.Add(item9);

            info[0] = "可用物理内存总量(M)";
            info[1] = (My.Info.AvailablePhysicalMemory / 1024 / 1024).ToString();
            ListViewItem item10 = new ListViewItem(info, "可用物理内存总量(M)");

            lv.Items.Add(item10);

            info[0] = "可用虚拟内存总量(M)";
            info[1] = (My.Info.AvailableVirtualMemory / 1024 / 1024).ToString();
            ListViewItem item11 = new ListViewItem(info, "可用虚拟内存总量(M)");

            lv.Items.Add(item11);

            info[0] = "系统驱动器";
            info[1] = Environment.GetEnvironmentVariable("SystemDrive");
            ListViewItem item12 = new ListViewItem(info, "系统驱动器");

            lv.Items.Add(item12);

            info[0] = "桌面目录";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            ListViewItem item13 = new ListViewItem(info, "系统驱动器");

            lv.Items.Add(item13);

            info[0] = "用户程序组目录";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
            ListViewItem item14 = new ListViewItem(info, "用户程序组目录");

            lv.Items.Add(item14);

            info[0] = "收藏夹目录";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
            ListViewItem item15 = new ListViewItem(info, "收藏夹目录");

            lv.Items.Add(item15);

            info[0] = "Internet历史记录";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.History);
            ListViewItem item16 = new ListViewItem(info, "Internet历史记录");

            lv.Items.Add(item16);

            info[0] = "Internet临时文件";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
            ListViewItem item17 = new ListViewItem(info, "Internet临时文件");

            lv.Items.Add(item17);
        }
Beispiel #22
0
 public static bool MyCopyFile(Task buildTask, string sourceFile, string targetFile, bool overWrite = true, bool onlyReplaceWithNewerFile = false, string logText = "Copying file from '{0}' to '{1}'...", bool continueOnError = false)
 {
     var myComputer = new Computer();
     bool flag = true;
     if (overWrite && onlyReplaceWithNewerFile)
     {
         flag = FileShouldBeCopied(sourceFile, targetFile);
         if (!flag)
         {
             MyLogMessage(buildTask, string.Format("Skipping file copy operation from '{0}' to '{1}' because the source file was the same version or older than the target file.", sourceFile, targetFile), MessageImportance.Normal);
         }
     }
     if (flag && !overWrite)
     {
         flag = !myComputer.FileSystem.FileExists(targetFile);
         if (!flag)
         {
             MyLogMessage(buildTask, string.Format("Skipping file copy operation from '{0}' to '{1}' because the target file already exists and the overwrite flag is set to false.", sourceFile, targetFile), MessageImportance.Normal);
         }
     }
     if (flag)
     {
         MyLogMessage(buildTask, string.Format(logText, sourceFile, targetFile), MessageImportance.Normal);
         try
         {
             myComputer.FileSystem.CopyFile(sourceFile, targetFile, true);
         }
         catch (UnauthorizedAccessException exception1)
         {
             ProjectData.SetProjectError(exception1);
             UnauthorizedAccessException exception = exception1;
             if (File.Exists(targetFile))
             {
                 MyLogWarning(buildTask, string.Format("File '{0}' is read-only. Its attributes will be changed to normal.", targetFile));
                 try
                 {
                     File.SetAttributes(targetFile, FileAttributes.Normal);
                 }
                 catch (Exception exception4)
                 {
                     ProjectData.SetProjectError(exception4);
                     ProjectData.ClearProjectError();
                 }
                 try
                 {
                     myComputer.FileSystem.CopyFile(sourceFile, targetFile, true);
                     goto Label_00FF;
                 }
                 catch (Exception exception5)
                 {
                     ProjectData.SetProjectError(exception5);
                     Exception exception2 = exception5;
                     if (!continueOnError)
                     {
                         throw;
                     }
                     MyLogWarning(buildTask, string.Format("Copying '{0}' to '{1}' failed: {2}.", sourceFile, targetFile, exception.Message));
                     ProjectData.ClearProjectError();
                     goto Label_00FF;
                 }
             }
             throw;
         Label_00FF:
             ProjectData.ClearProjectError();
         }
         catch (Exception exception6)
         {
             ProjectData.SetProjectError(exception6);
             Exception exception3 = exception6;
             if (!continueOnError)
             {
                 throw;
             }
             MyLogWarning(buildTask, string.Format("Copying '{0}' to '{1}' failed: {2}.", sourceFile, targetFile, exception3.Message));
             ProjectData.ClearProjectError();
         }
     }
     return flag;
 }
 private void MainForm_Load(object sender, EventArgs e)
 {
     Computer com = new Computer();
     if (com.Ports.SerialPortNames.Count != 0)
     {
         cbPortName.Items.Clear();
         foreach (string str in com.Ports.SerialPortNames)
             cbPortName.Items.Add(str);
     }
     _serialPort = new SerialPort();
     _serialPort.DataReceived += DataReceivedHandler;
     tmrDateTime.Start();
 }
Beispiel #24
0
 public static void MyCreateFolder(Task buildTask, string folderName, string logText = "About to create folder '{0}'")
 {
     var myComputer = new Computer();
     if (!Directory.Exists(folderName))
     {
         MyLogMessage(buildTask, string.Format(logText, folderName), MessageImportance.Normal);
         myComputer.FileSystem.CreateDirectory(folderName);
     }
 }
Beispiel #25
0
 public static void CopyDirectory(DirectoryInfo source, DirectoryInfo target)
 {
     var c = new Computer();
     c.FileSystem.CopyDirectory(source.FullName, target.FullName, true);
 }
Beispiel #26
0
 public static void MyDeleteFolder(Task buildTask, string folderName, DeleteDirectoryOption OnDirectoryNotEmpty, bool failOnError, string logText)
 {
     var myComputer = new Computer();
     if (Directory.Exists(folderName))
     {
         if (Strings.Len(logText) > 0)
         {
             MyLogMessage(buildTask, string.Format(logText, folderName), MessageImportance.Normal);
         }
         try
         {
             myComputer.FileSystem.DeleteDirectory(folderName, OnDirectoryNotEmpty);
         }
         catch (UnauthorizedAccessException exception1)
         {
             ProjectData.SetProjectError(exception1);
             UnauthorizedAccessException exception = exception1;
             if (OnDirectoryNotEmpty == DeleteDirectoryOption.DeleteAllContents)
             {
                 foreach (string str in Directory.GetFiles(folderName, "*.*", System.IO.SearchOption.AllDirectories))
                 {
                     MyDeleteFile(str, true);
                 }
                 MyDeleteFolder(buildTask, folderName, DeleteDirectoryOption.ThrowIfDirectoryNonEmpty, failOnError, logText);
             }
             ProjectData.ClearProjectError();
         }
         catch (IOException exception4)
         {
             ProjectData.SetProjectError(exception4);
             IOException exception2 = exception4;
             if ((Strings.InStr(exception2.Message, "is not empty", CompareMethod.Binary) > 0) && (OnDirectoryNotEmpty == DeleteDirectoryOption.DeleteAllContents))
             {
                 foreach (string str2 in Directory.GetDirectories(folderName, "*", System.IO.SearchOption.TopDirectoryOnly))
                 {
                     MyDeleteFolder(buildTask, str2, DeleteDirectoryOption.ThrowIfDirectoryNonEmpty, failOnError, logText);
                 }
             }
             else
             {
                 if (failOnError)
                 {
                     throw;
                 }
                 MyLogWarning(buildTask, string.Format("Deleting folder '{0}' failed with exception '{1}'. The exception type was '{2}'. This may result in a later build error.", folderName, exception2.Message, exception2.GetType().Name));
             }
             ProjectData.ClearProjectError();
         }
         catch (Exception exception5)
         {
             ProjectData.SetProjectError(exception5);
             Exception exception3 = exception5;
             if (failOnError)
             {
                 throw;
             }
             MyLogWarning(buildTask, string.Format("Deleting folder '{0}' failed with exception '{1}'. The exception type was '{2}'. This may result in a later build error.", folderName, exception3.Message, exception3.GetType().Name));
             ProjectData.ClearProjectError();
         }
     }
 }