|
191
|
Programación / .NET (C#, VB.NET, ASP) / Leer bits de Byte
|
en: 2 Abril 2021, 13:14 pm
|
Buenas camaradas: Haciendo un programa hecho con Windows Form bajo .Net FrameWotk 4.7. Si envío un comando por el puerto serie que se llama X82, recibo un mensaje que en ASCII no se entiende porque usa caracteres raros. Lo paso a hexadecimal y en binario. Envío un comando, ocurre algún evento y en Windoes Form me aparece cógios en HEX y en BIN. Se puede cambiar varios bit en un único Byte. Por ejemplo, si me llega este dato. Hexadecimal: 23C797C0B00D Binario: 00100011 11000111 10010111 11000000 10110000 00001101 Un ejemplo, es poner muchos labels en cada bits y una tabla de cada Byte recibido. Simpre son la misma cantidad de bytes ya que en realdiad hace de Flags. Centrándonos en el binario, ya que hay 6 Bytes. 00100011 11000111 10010111 11000000 10110000 00001101 -------- -------- -------- -------- -------- -------- Byte I Byte a Byte b Byte c Byte d Byte F
En el Byte c que corresponde al 11000000 quiero leer el bit 3 que corresponde al "Extractor" indicado en la tabla de abajo. Cada Byte tiene su tabla, ahora nos centramos en un Byte y ver los estados de los bits. bit:c Dato Función.7 = 1 Motor A. 6 = 1 Motor B. 5 = 0 Luz A. 4 = 0 Luz B. 3 = 0 Extractor. 2 = 0 Alarma. 1 = 0 Persiana. 0 = 0 Ventilador El Byte c que ahora contiene estos bits que son 11000000, me llega una nueva trama de Bytes y precisamente este, cambia de 11000000 a 11001000. Solo ha cambiado un bit que es el 3 en el Byte c. Cada bit tiene su label para mostrarlo en el formulario de Windows. La tabla de abajo se actualiza. bit:c Dato Función.7 = 1 Motor A. 6 = 1 Motor B. 5 = 0 Luz A. 4 = 0 Luz B. 3 = 1 Extractor. 2 = 0 Alarma. 1 = 0 Persiana. 0 = 0 Ventilador Antes el Byte c del bit 3 que es el Extractor estaba a 0, ahora es 1. En resumen. Quiero saber como se leen los bits que me llegan del puerto serie. ¿Existe la posibilidad de hacer un programa así? Saludos. PD: En esta clase de programas que no suelo usar, es como las aves, fáciles de ver, difíciles de alcanzar.
|
|
|
192
|
Programación / .NET (C#, VB.NET, ASP) / Re: Separar binario por cada byte
|
en: 2 Abril 2021, 10:33 am
|
Buenas: Como veo la base ya tienes una variable con 0 y 1. Hice el foreach y for que indicaste. Me da problemas. Lo hice así para que lo pase a binario y elfor tuyo para que lo separe. Ver zoom. // Pasar a binario. string resultado = ""; foreach (string leer in recibidos.Select(c => Convert.ToString(c, 2))) { resultado += leer.ToString(); } for (int i = 0; i < resultado.Length; i += 8) { richTextBox1.Text += resultado.Substring(i, 8) + " "; }
Si lo hago solo así que se muestre en richTextBox me da el mismo error. for (int i = 0; i < recibidos.Length; i += 8) { richTextBox1.Text += recibidos.Substring(i, 8) + " "; }
|
|
|
193
|
Programación / .NET (C#, VB.NET, ASP) / Re: Separar binario por cada byte
|
en: 2 Abril 2021, 05:33 am
|
Buenas mi muy distinguido amigo: El problema que el código y variable recibidos me viene en string. Lo he intentado poner en Byte y me da más problemas por todas partes. El código es enorme. Dejo un ejemplo para que lo veas y te hagas una gran idea. using System; using System.IO.Ports; using System.Linq; using System.Text; using System.Windows.Forms; namespace Ejemplo { public partial class Form1 : Form { // Utilizaremos un string como buffer de recepción. string recibidos; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { try { // Codificación. //serialPort1.Encoding = Encoding.GetEncoding(437); //serialPort1.Encoding = Encoding.GetEncoding(28591); // 28591 es lo mismo que ISO-8859-1. serialPort1.Encoding = Encoding.GetEncoding("ISO-8859-1"); // Añado los puertos disponible en el PC con SerialPort.GetPortNames() al comboBox_Puerto. comboBox_Puerto.DataSource = SerialPort.GetPortNames(); // Añade puertos disponibles físicos y virtuales. serialPort1.PortName = comboBox_Puerto.Text.ToString(); // Añadir datos recibidos en el evento. serialPort1 .DataReceived += new SerialDataReceivedEventHandler (serialPort1_DataReceived ); } catch (Exception error) { MessageBox.Show(error.Message, "Aviso:", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } // Detecta USB o puerto serie virtual cuando lo conecta y desconecta del cable. protected override void WndProc(ref Message USB) { if (USB.Msg == 0x219) { comboBox_Puerto.DataSource = SerialPort.GetPortNames(); } // Detecta si hay cambios en el usb y si los hay los refleja. base.WndProc(ref USB); } private void button_Conectar_Click(object sender, EventArgs e) { try { serialPort1.PortName = comboBox_Puerto.Text.ToString(); // Puerto seleccionado previamente. serialPort1.BaudRate = Convert.ToInt32(comboBox_Baudios.Text); // Baudios. serialPort1.Open(); // Abrir puerto. comboBox_Puerto.Enabled = false; comboBox_Baudios.Enabled = false; button_Conectar.Enabled = false; button_Desconectar.Enabled = true; groupBox_Control_Zumbador.Enabled = true; } catch (Exception error) { MessageBox.Show(error.Message, "Aviso:", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void button_Desconectar_Click(object sender, EventArgs e) { try { serialPort1.Close(); // Cerrar puerto. comboBox_Puerto.Enabled = true; comboBox_Baudios.Enabled = true; button_Conectar.Enabled = true; button_Desconectar.Enabled = false; groupBox_Control_Zumbador.Enabled = false; } catch (Exception error) { MessageBox.Show(error.Message, "Aviso:", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } // Al cerrar el formulario, cierra el puerto si está abierto. private void Form1_FormClosing(object sender, FormClosingEventArgs e) { try { serialPort1.Close(); // Cerrar puerto. } catch (Exception error) { MessageBox.Show(error.Message, "Aviso:", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } // Al recibir datos. private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { // Acumula los caracteres recibidos a nuestro 'buffer' (string). recibidos += serialPort1.ReadExisting(); // Invocar o llamar al proceso de tramas. Invoke (new EventHandler (Actualizar )); } // Procesar los datos recibidos en el bufer y extraer tramas completas. private void Actualizar(object sender, EventArgs e) { // Asignar el valor de la trama al richTextBox. richTextBox1.Text += recibidos; // Pasar a hexadecimal. foreach (byte b in recibidos) { // x = minúscula, X = mayúscula. richTextBox1.Text += b.ToString("X2"); } // Nueva línea. richTextBox1.Text += Environment.NewLine; // Pasar a binario. foreach (string leer in recibidos.Select(c => Convert.ToString(c, 2))) { richTextBox1.Text += leer.ToString(); } // Nueva línea. richTextBox1.Text += Environment.NewLine; richTextBox1.Text += Environment.NewLine; // Selecciona la posición final para leer los mensajes entrantes. richTextBox1.SelectionStart = richTextBox1.Text.Length; // Mantiene el scroll en la entrada de cada mensaje. richTextBox1.ScrollToCaret(); // Limpiar. recibidos = ""; } private void button_Activar_Click(object sender, EventArgs e) { //byte[] mBuffer = Encoding.ASCII.GetBytes("K60:1\r"); // Comando K60:1 activar. byte[] mBuffer = Encoding.ASCII.GetBytes("X87\r"); // Comando X87 Flags. serialPort1.Write(mBuffer, 0, mBuffer.Length); } private void button_Desactivar_Click(object sender, EventArgs e) { byte[] mBuffer = Encoding.ASCII.GetBytes("K60:0\r"); // Comando K60:0 desactivar. serialPort1.Write(mBuffer, 0, mBuffer.Length); } private void button_Mute_temporal_Click(object sender, EventArgs e) { byte[] mBuffer = Encoding.ASCII.GetBytes("B\r"); // Comando K60:2 Mute temporal. serialPort1.Write(mBuffer, 0, mBuffer.Length); } private void button_Limpiar_Click(object sender, EventArgs e) { // Limpiar. richTextBox1.Clear(); } } }
|
|
|
194
|
Programación / .NET (C#, VB.NET, ASP) / Separar binario por cada byte
|
en: 1 Abril 2021, 19:15 pm
|
Hola: Al mostrar una trama de bytes, lo presento en binario y me muestra esto. 001000111100011110010111110000001011000000001101Hay 6 Bytes que en realidad en hexadecimal es 23 C7 97 C0 B0 0DQuiero que se me separe así en cada byte o cada 8 bit. 00100011 11000111 10010111 11000000 10110000 00001101He intentado hacerlo con este código: // Pasar a binario. foreach (string leer in recibidos.Select(c => Convert.ToString(c, 2))) { richTextBox1.Text += leer.ToString(); }
Me pasa dos cosas. Como en el ejemplo de arriba, si los bits empieza por cero y encuentro un uno, por ejemplo. 00000001, en la pantalla me aparece solo el 1 ignorando los sietes primeros 0. Me gusta más que se muestre así 00000001 en vez de tipo ahorrador con solo un 1. La otra cosa, que por cada 8 bytes en binario se muestre separado como indicado arriba. ¿Es posible hacerlo? Gracias.
|
|
|
195
|
Programación / .NET (C#, VB.NET, ASP) / Re: Leer información de una SAI / UPS
|
en: 1 Abril 2021, 05:28 am
|
Buenas: Me está dando resultados diferentes de un terminal que el propio mio en hexadecimal y no se el motivo. Cuando los datos recibidos son los mismos. Ver Zoom. Quiero saber el motivo. Muchas gracias. Configuración puerto serie. Ver zoom. Código C#:using System; using System.IO.Ports; using System.Linq; using System.Text; using System.Windows.Forms; namespace Terminal_UPS_SAI_02 { public partial class Form1 : Form { // Utilizaremos un string como buffer de recepción. string recibidos; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { try { // Añado los puertos disponible en el PC con SerialPort.GetPortNames() al comboBox_Puerto. comboBox_Puerto.DataSource = SerialPort.GetPortNames(); // Añade puertos disponibles físicos y virtuales. serialPort1.PortName = comboBox_Puerto.Text.ToString(); // Añadir en la variable recibidos datos codificados. recibidos += serialPort1.Encoding = Encoding.GetEncoding(437); // Añadir datos recibidos en el evento. serialPort1 .DataReceived += new SerialDataReceivedEventHandler (serialPort1_DataReceived ); } catch { MessageBox.Show("No encuentra ningún puerto físico ni virtual.", "Aviso:", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } // Detecta USB o puerto serie virtual cuando lo conecta y desconecta del cable. protected override void WndProc(ref Message USB) { if (USB.Msg == 0x219) { comboBox_Puerto.DataSource = SerialPort.GetPortNames(); } // Detecta si hay cambios en el usb y si los hay los refleja. base.WndProc(ref USB); } private void button_Conectar_Click(object sender, EventArgs e) { try { serialPort1.PortName = comboBox_Puerto.Text.ToString(); // Puerto seleccionado previamente. serialPort1.BaudRate = Convert.ToInt32(comboBox_Baudios.Text); // Baudios. serialPort1.Open(); // Abrir puerto. comboBox_Puerto.Enabled = false; comboBox_Baudios.Enabled = false; button_Conectar.Enabled = false; button_Desconectar.Enabled = true; groupBox_Control_Zumbador.Enabled = true; } catch (Exception error) { MessageBox.Show(error.Message, "Aviso:", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void button_Desconectar_Click(object sender, EventArgs e) { try { serialPort1.Close(); // Cerrar puerto. comboBox_Puerto.Enabled = true; comboBox_Baudios.Enabled = true; button_Conectar.Enabled = true; button_Desconectar.Enabled = false; groupBox_Control_Zumbador.Enabled = false; } catch (Exception error) { MessageBox.Show(error.Message, "Aviso:", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } // Al cerrar el formulario, cierra el puerto si está abierto. private void Form1_FormClosing(object sender, FormClosingEventArgs e) { try { serialPort1.Close(); // Cerrar puerto. } catch (Exception error) { MessageBox.Show(error.Message, "Aviso:", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } // Al recibir datos. private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { // Acumula los caracteres recibidos a nuestro 'buffer' (string). recibidos += serialPort1.ReadExisting(); // Invocar o llamar al proceso de tramas. Invoke (new EventHandler (Actualizar )); } // Procesar los datos recibidos en el bufer y extraer tramas completas. private void Actualizar(object sender, EventArgs e) { // Asignar el valor de la trama al richTextBox. richTextBox1.Text += recibidos; // Pasar a hexadecimal. foreach (byte b in recibidos) { // x = minúscula, X = mayúscula. richTextBox1.Text += b.ToString("X2"); } // Nueva línea. richTextBox1.Text += Environment.NewLine; // Pasar a binario. foreach (string leer in recibidos.Select(c => Convert.ToString(c, 2))) { richTextBox1.Text += leer.ToString(); } // Nueva línea. richTextBox1.Text += Environment.NewLine; richTextBox1.Text += Environment.NewLine; // Selecciona la posición final para leer los mensajes entrantes. richTextBox1.SelectionStart = richTextBox1.Text.Length; // Mantiene el scroll en la entrada de cada mensaje. richTextBox1.ScrollToCaret(); // Limpiar. recibidos = ""; } private void button_Activar_Click(object sender, EventArgs e) { //byte[] mBuffer = Encoding.ASCII.GetBytes("K60:1\r"); // Comando K60:1 activar. byte[] mBuffer = Encoding.ASCII.GetBytes("X87\r"); // Comando X87 Flags. serialPort1.Write(mBuffer, 0, mBuffer.Length); } private void button_Desactivar_Click(object sender, EventArgs e) { byte[] mBuffer = Encoding.ASCII.GetBytes("K60:0\r"); // Comando K60:0 desactivar. serialPort1.Write(mBuffer, 0, mBuffer.Length); } private void button_Mute_temporal_Click(object sender, EventArgs e) { byte[] mBuffer = Encoding.ASCII.GetBytes("K60:2\r"); // Comando K60:2 Mute temporal. serialPort1.Write(mBuffer, 0, mBuffer.Length); } private void button_Limpiar_Click(object sender, EventArgs e) { // Limpiar. richTextBox1.Clear(); } } }
¿Alguna idea? Saludos camaradas.
|
|
|
197
|
Programación / .NET (C#, VB.NET, ASP) / Re: Añadir elementos al comboBox
|
en: 29 Marzo 2021, 21:25 pm
|
Buenas: Lo he intentado hacerlo en Windows Form con.Net 5.0. Código fuente C#:using System; using System.Management; // No olvidar y añadir en Dependencias, NuGet. using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace Lector_discos_Net_5_01_cs { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // Variable. public static string datos = ""; [DllImport("winmm.dll")] public static extern Int32 mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int uReturnLength, IntPtr hwndCallback); StringBuilder rt = new StringBuilder (127); private void button_Abrir_Click(object sender, EventArgs e) { label_Mensaje.Text = "Abriendo..."; Application.DoEvents(); discoSiNo(); mciSendString("set CDAudio!" + comboBox_Unidad.Text + " door open", rt, 127, IntPtr.Zero); /* Si quieres por ejemplo elegir la unidad que quieras, en este caso la H, se le asigana !H como indica abajo. En vez de CDAudio, CDAudio!H. mciSendString("set CDAudio!H door open", rt, 127, IntPtr.Zero); */ label_Mensaje.Text = "Abierto."; } private void button_Cerrar_Click(object sender, EventArgs e) { label_Mensaje.Text = "Cerrando..."; Application.DoEvents(); mciSendString("set CDAudio!" + comboBox_Unidad.Text + " door closed", rt, 127, IntPtr.Zero); label_Mensaje.Text = "Cerrado."; label_Mensaje_disco.Text = "Disco en el lector: Leyendo..."; discoSiNo(); } // Lectura de dispositivos. void ConsigueComponentes(string hwclass, string syntax) { ManagementObjectSearcher mos = new ManagementObjectSearcher ("root\\CIMV2", "SELECT * FROM " + hwclass ); foreach (ManagementObject mj in mos.Get()) { if (Convert.ToString(mj[syntax]) != "") { datos = Convert.ToString(mj[syntax]); } } } // Comprobar si hay disco en el lector. void discoSiNo() { // Disco en la unidad del lector. ConsigueComponentes("Win32_CDROMDrive", "MediaLoaded"); // ¿Disco en el lector? if (datos == "True") { label_Mensaje_disco.Text = "Disco en el lector: Sí."; } else { label_Mensaje_disco.Text = "Disco en el lector: No."; } // Limpiar. datos = ""; } private void Form1_Load(object sender, EventArgs e) { discoSiNo(); // Nombre de la unidad. ConsigueComponentes("Win32_CDROMDrive", "Id"); comboBox_Unidad.Items.Add(datos); comboBox_Unidad.Text = datos.ToString(); } } }
Código WindowsForm .Net 5.0:namespace Lector_discos_Net_5_01_cs { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button_Abrir = new System.Windows.Forms.Button(); this.button_Cerrar = new System.Windows.Forms.Button(); this.groupBox_Bandeja = new System.Windows.Forms.GroupBox(); this.label_Mensaje = new System.Windows.Forms.Label(); this.comboBox_Unidad = new System.Windows.Forms.ComboBox(); this.label_Unidad = new System.Windows.Forms.Label(); this.label_Mensaje_disco = new System.Windows.Forms.Label(); this.groupBox_Bandeja.SuspendLayout(); this.SuspendLayout(); // // button_Abrir // this.button_Abrir.Location = new System.Drawing.Point(32, 146); this.button_Abrir.Name = "button_Abrir"; this.button_Abrir.Size = new System.Drawing.Size(92, 47); this.button_Abrir.TabIndex = 0; this.button_Abrir.Text = "&Abrir"; this.button_Abrir.UseVisualStyleBackColor = true; this.button_Abrir.Click += new System.EventHandler(this.button_Abrir_Click); // // button_Cerrar // this.button_Cerrar.Location = new System.Drawing.Point(155, 146); this.button_Cerrar.Name = "button_Cerrar"; this.button_Cerrar.Size = new System.Drawing.Size(92, 47); this.button_Cerrar.TabIndex = 1; this.button_Cerrar.Text = "&Cerrar"; this.button_Cerrar.UseVisualStyleBackColor = true; this.button_Cerrar.Click += new System.EventHandler(this.button_Cerrar_Click); // // groupBox_Bandeja // this.groupBox_Bandeja.Controls.Add(this.label_Mensaje); this.groupBox_Bandeja.Location = new System.Drawing.Point(12, 12); this.groupBox_Bandeja.Name = "groupBox_Bandeja"; this.groupBox_Bandeja.Size = new System.Drawing.Size(249, 117); this.groupBox_Bandeja.TabIndex = 2; this.groupBox_Bandeja.TabStop = false; this.groupBox_Bandeja.Text = "Bandeja:"; // // label_Mensaje // this.label_Mensaje.AutoSize = true; this.label_Mensaje.Font = new System.Drawing.Font("Segoe UI", 27 .75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); this.label_Mensaje.Location = new System.Drawing.Point(20, 40); this.label_Mensaje.Name = "label_Mensaje"; this.label_Mensaje.Size = new System.Drawing.Size(54, 50); this.label_Mensaje.TabIndex = 0; this.label_Mensaje.Text = "¿?"; // // comboBox_Unidad // this.comboBox_Unidad.FormattingEnabled = true; this.comboBox_Unidad.Location = new System.Drawing.Point(310, 159); this.comboBox_Unidad.Name = "comboBox_Unidad"; this.comboBox_Unidad.Size = new System.Drawing.Size(121, 23); this.comboBox_Unidad.TabIndex = 3; // // label_Unidad // this.label_Unidad.AutoSize = true; this.label_Unidad.Location = new System.Drawing.Point(310, 132); this.label_Unidad.Name = "label_Unidad"; this.label_Unidad.Size = new System.Drawing.Size(48, 15); this.label_Unidad.TabIndex = 4; this.label_Unidad.Text = "Unidad:"; // // label_Mensaje_disco // this.label_Mensaje_disco.AutoSize = true; this.label_Mensaje_disco.Font = new System.Drawing.Font("Segoe UI", 21 .75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); this.label_Mensaje_disco.Location = new System.Drawing.Point(12, 198); this.label_Mensaje_disco.Name = "label_Mensaje_disco"; this.label_Mensaje_disco.Size = new System.Drawing.Size(269, 40); this.label_Mensaje_disco.TabIndex = 5; this.label_Mensaje_disco.Text = "Disco en el lector: "; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(463, 247); this.Controls.Add(this.label_Mensaje_disco); this.Controls.Add(this.label_Unidad); this.Controls.Add(this.comboBox_Unidad); this.Controls.Add(this.button_Abrir); this.Controls.Add(this.groupBox_Bandeja); this.Controls.Add(this.button_Cerrar); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Lector disco C# 2019 - .Net 5.0"; this.Load += new System.EventHandler(this.Form1_Load); this.groupBox_Bandeja.ResumeLayout(false); this.groupBox_Bandeja.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button_Abrir; private System.Windows.Forms.Button button_Cerrar; private System.Windows.Forms.GroupBox groupBox_Bandeja; private System.Windows.Forms.Label label_Mensaje; private System.Windows.Forms.ComboBox comboBox_Unidad; private System.Windows.Forms.Label label_Unidad; private System.Windows.Forms.Label label_Mensaje_disco; } }
Aquí se trata que no me sale. Es que tengo dos unidades de disco CD-ROM / DVD-ROM. Se me agrega solo la F:, Falta la G:, pero siempre que sea sea unidad de disco. Saludos.
|
|
|
199
|
Programación / Scripting / Recibir mensajes
|
en: 28 Marzo 2021, 14:39 pm
|
Quiero recibir mensajes desde el puerto serie usando CMD de Windwos. Creo un Script gracias a los compañeros de este foro en su día. title Arduino CMD y puerto serie MODE.com COM4 BAUD=115200 PARITY=n DATA=8 STOP=1 :Menu CLS CHOICE.exe /C "123" /M " Escoge una opción " ) )
La cuestión es. ¿Cómo se recibe un mensaje desde el otro lado del puerto serie? Saludos.
|
|
|
200
|
Programación / .NET (C#, VB.NET, ASP) / ¿Cómo listar solo unidades DVD y ver su información?
|
en: 28 Marzo 2021, 12:12 pm
|
Quiero hacer un programa en consola C#, en el cual me muestre cuantas hay y su información. Solo quiero que me muestre unidades de discos DVD, aunque sean SATA, IDE o por USB. Por ejemplo: Unidad F: Etiqueta de volumen : 58 Fotos 2020 Tamaño total de la unidad: 4,26 GB.
Unidad G: Etiqueta de volumen : Visual Tamaño total de la unidad: 3,09 GB. Quiero hacerlo así y ya está. El ejemplo que he visto te cuenta todas las unidades como indica abajo y no me interesa. using System; using System.IO; namespace Informacion_lector_Consola_01 { class Program { static void Main(string[] args) { #region Configuración ventana. // Título de la ventana. Console.Title = "Información lector."; // Tamaño de la ventana, x, y. Console.SetWindowSize(80, 35); // Color de fondo. Console.BackgroundColor = ConsoleColor.White; // Color de las letras. Console.ForegroundColor = ConsoleColor.Black; // Limpiar pantalla y dejarlo todo en color de fondo. Console.Clear(); // Visible el cursor. Console.CursorVisible = true; #endregion DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { Console.WriteLine("Unidad {0}", d.Name); Console.WriteLine(" Tipo de unidad: {0}", d.DriveType); if (d.IsReady == true) { Console.WriteLine(" Etiqueta de volumen : {0}", d.VolumeLabel); Console.WriteLine(" Sistema de archivo: {0}", d.DriveFormat); Console.WriteLine( " Espacio disponible para el usuario actual:{0, 15} bytes", d.AvailableFreeSpace); Console.WriteLine( " Espacio total disponible: {0, 15} bytes", d.TotalFreeSpace); Console.WriteLine( " Tamaño total de la unidad: {0, 15} bytes ", d.TotalSize); } } // Pulse cualquier tecla para continuar. Console.ReadKey(); } } }
¿Alguna idea? Saludos.
|
|
|
|
|
|
|