如何从csv文件中检索数据并放入相应的文本框中

时间:2014-11-03 09:27:54

标签: c# .net wpf xaml

我已经使用3个文本框分别从textbox2,textbox3&中的特定文件夹中提取文件名,文件扩展名和路径。 TextBox1的。此数据存储在.csv文件中。

问题1:当我按下按钮6时,我想在读取此.csv文件时在各自的文本框中提取此数据。

问题2:如何显示相对路径而不是显示完整路径? (我认为substring方法可用于此问题,但如何:|)

例如:

显示Chrome\Application\38.0.2125.104\fileA.exe
     或Update\1.3.24.15\fileB.exe

而不是显示

C:\Program Files (x86)\Google\Chrome\Application\38.0.2125.104\fileA.exe

OR

C:\Program Files (x86)\Google\Update\1.3.24.15\fileB.exe

XAML代码

<Window x:Class="FileFinder.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="FileCopier"
    WindowStartupLocation="CenterScreen" Width="1366" Height="758">
<Grid Background="LavenderBlush">

    <Label Height="40" Margin="240,0,234,0" Name="label1" VerticalAlignment="Top" FontSize="28" HorizontalContentAlignment="Center" Foreground="DarkSeaGreen" FontWeight="Bold" FontFamily="Broadway">Welcome To</Label>

    <Label Height="55" Margin="194,35,194,0" Name="label2" VerticalAlignment="Top" HorizontalContentAlignment="Center" FontWeight="Bold" FontSize="45" Foreground="Chocolate" FontFamily="Colonna MT">FILE FINDER</Label>

    <TextBox IsReadOnly="True" AutoWordSelection="True" VerticalScrollBarVisibility="Auto" Margin="475.857,211,20,21" Name="textbox1" Background="LavenderBlush" Opacity="0.7" ScrollBar.Scroll="Scroll" BorderThickness="0" FontSize="16" TextWrapping="Wrap"></TextBox>

    <Button ToolTip="Click to search exe files" Height="45" HorizontalAlignment="Left" Margin="366,96,0,0" Name="button1" VerticalAlignment="Top" Width="112" Background="LavenderBlush" BorderThickness="1" BorderBrush="DarkSeaGreen" FontSize="24" FontWeight="Bold" Foreground="DarkSeaGreen" Click="button1_Click" FontFamily="Broadway" Cursor="Hand">.exe</Button>

    <Button ToolTip="Click to search dll files" Margin="602,96,0,0" Name="button2" Background="LavenderBlush" BorderBrush="DarkSeaGreen" Foreground="DarkSeaGreen" FontSize="24" FontWeight="Bold" Click="button2_Click" FontFamily="Broadway" Cursor="Hand" Height="45" VerticalAlignment="Top" HorizontalAlignment="Left" Width="123">.dll</Button>

    <Button Background="LavenderBlush" BorderBrush="DarkSeaGreen" FontSize="24" FontWeight="Bold" Foreground="DarkSeaGreen" Height="45" HorizontalAlignment="Right" Margin="0,96,383,0" Name="button3" VerticalAlignment="Top" Width="122" Click="button3_Click" FontFamily="Broadway">All</Button>

    <Label FontFamily="Broadway" FontSize="28" FontWeight="Bold" Foreground="Black" Height="40" HorizontalContentAlignment="Center" Margin="12,165,0,0" Name="label3" VerticalAlignment="Top" HorizontalAlignment="Left" Width="230.069" Opacity="0.6">Filename</Label>

    <Label FontFamily="Broadway" FontSize="28" FontWeight="Bold" Foreground="Black" Height="40" HorizontalContentAlignment="Center" Margin="0,165,234,0" Name="label4" VerticalAlignment="Top" Opacity="0.6" HorizontalAlignment="Right" Width="86.627">Path</Label>

    <Button  Name="button4" Click="button4_Click" Width="32" Height="32" HorizontalAlignment="Right" Margin="0,173,175,0" VerticalAlignment="Top" BorderThickness="0" Background="LavenderBlush" ToolTip="PageUp">
        <StackPanel>
            <Image Source="C:\Users\Vipul.Sharma\Documents\Visual Studio 2008\Projects\FileFinder\FileFinder\PageUp.png"></Image>
        </StackPanel>
    </Button>

    <Button Name="button5" Click="button5_Click" Width="32" Height="32" HorizontalAlignment="Right" Margin="0,173,140,0" VerticalAlignment="Top" BorderThickness="0" Background="LavenderBlush" ToolTip="PageUp">
        <StackPanel>
            <Image Source="C:\Users\Vipul.Sharma\Documents\Visual Studio 2008\Projects\FileFinder\FileFinder\PageDown.png" Opacity="0.7"></Image>
        </StackPanel>
    </Button>

    <TextBox IsReadOnly="True" AutoWordSelection="True" VerticalScrollBarVisibility="Visible" Margin="20,211,0,21" Name="textbox2" Background="LavenderBlush" Opacity="0.7" ScrollBar.Scroll="Scroll" BorderThickness="0" FontSize="16" TextWrapping="Wrap" HorizontalAlignment="Left" Width="345.818"></TextBox>
    <TextBox IsReadOnly="True" AutoWordSelection="True" VerticalScrollBarVisibility="Visible" HorizontalAlignment="Left" Margin="371.54,211,0,21" Name="textBox3" Width="106.46" Background="LavenderBlush" Opacity="0.7" ScrollBar.Scroll="Scroll" BorderThickness="0" FontSize="16" TextWrapping="Wrap"></TextBox>
    <Label FontFamily="Broadway" FontSize="28" FontWeight="Bold" Foreground="Black" Height="40" HorizontalAlignment="Left" HorizontalContentAlignment="Center" Margin="305.806,165.764,0,0" Name="label5" Opacity="0.6" VerticalAlignment="Top" Width="230.069">Extension</Label>
    <Button Background="LavenderBlush" BorderBrush="DarkSeaGreen" FontFamily="Broadway" FontSize="24" FontWeight="Bold" Foreground="DarkSeaGreen" Height="45" HorizontalAlignment="Right" Margin="0,95.743,143,0" Name="button6" VerticalAlignment="Top" Width="122" Click="button6_Click">GetFile</Button>
</Grid>

C#代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Controls.Primitives;

namespace FileFinder
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            List<String> files = new List<String>();
            String[] extensions = new[] { "*.exe" };

            foreach (String extension in extensions)
            {
                String[] lol = Directory.GetFiles(@"mypath", "*.exe", SearchOption.AllDirectories);

            foreach (String file in lol)
                files.Add(file);
            }
            textbox1.Clear();
            textBox3.Clear();
            textbox1.Clear();
            for (int i = 0; i < files.Count; i++)
            {
            textbox2.Text += Path.GetFileNameWithoutExtension(files[i]) + "\n";
            textBox3.Text += Path.GetExtension(files[i]) + "\n";
            textbox1.Text += files[i] + "\n";
            }

           List<string> lstResult = new List<string>();
           for (int i = 0; i < files.Count; i++)
           {
                lstResult.Add(Path.GetFileNameWithoutExtension(files[i]) + "," + Path.GetExtension(files[i])+"," + Path.GetFullPath(files[i]));
           }
           File.WriteAllLines(@"C:\BigB.csv", lstResult.ToArray());

       }
    private void Scroll(object sender, ScrollEventArgs e)
    {
        if (sender == textbox1 || sender == textBox3)
        {
            textbox1.ScrollToVerticalOffset(e.NewValue);
            textBox3.ScrollToVerticalOffset(e.NewValue);
        }
        else
        {
            textbox1.ScrollToVerticalOffset(e.NewValue);
            textBox3.ScrollToVerticalOffset(e.NewValue);
        }
    }

   //WHAT I HAVE SEEN AND TRIED
   private void button6_Click(object sender, RoutedEventArgs e)
    {
        ReadCSV("BigB.csv");
        textbox2.Text += name;
        textbox1.Text += extension;
        textBox3.Text += path;
    }

    public class InOrder
    {
        public string name { get; set; }

        public string extension { get; set; }

        public string path { get; set; }

        public InOrder(string n, string ext, string p)
        {
            name = n;
            extension = ext;
            path = p;
        }
    }

    public IEnumerable<InOrder> ReadCSV(string fileName)
    {
        // We change file extension here to make sure it's a .csv file.
        string[] collectBack = File.ReadAllLines(System.IO.Path.ChangeExtension(@"C:\BigB.csv", ".csv"));

        // lines.Select allows me to project each line as a InOrder. 
        // This will give me an IEnumerable<InOrder> back.
        return 
        {
            string[] data = collectBack.Split(';');
            // We return a person with the data in order.
            return new InOrder(data[0], data[1], (data[2]));  
        });          
    }
}

2 个答案:

答案 0 :(得分:0)

您正在使用XAML,因此您应该绑定到您的控件而不是textbox2.Text = "something"。完成后,您不需要XAML代码中的任何“名称”属性。如果您确实需要命名,请使用正确的描述性名称:textbox2不会告诉我任何事情。

为什么{you>从未使用过foreach (String extension in extensions)

恕我直言extension中的大多数代码都应该移到单独的类中:一个类用于检索文件列表,另一个用于将文件列表写入文件。

为什么只需执行button1_Click for(int i = 0; i&lt; files.Count; i ++)?

为什么只需使用foreach (var file in files)的AddRange方法,就可以将Directory.GetFiles的结果存储在(命名错误的)变量lol中?

如果您想显示files而不是Update\1.3.24.15\fileB.exe,只需使用string.Replace方法将C:\Program Files (x86)\Google\Update\1.3.24.15\fileB.exe替换为C:\Program Files (x86)\Google\。您应该毫不费力地找到C#代码来读取文件的内容。

对我来说string.Empty是一个糟糕的类名,因为它没有告诉我它包含什么。 InOrderFileData更有意义。您应该更频繁地使用此类,例如而不是获取FileProperties,而是立即解析结果Directory.GetFiles并将其转换为List<String> files并在分配List<FileData>textbox2textBox3时对其进行迭代, ...

为什么要拨打textbox1

System.IO.Path.ChangeExtension会返回ReadCSV,但您不会循环显示结果。

为什么要在不使用IEnumerable<InOrder>时将filename传递给ReadCSV

public string name { get; set; }违反了Microsoft的命名规则:属性应为PascalCase。

答案 1 :(得分:0)

为什么要使用这些中间步骤?

List<string> lstResult = new List<string>();
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
StringBuilder sb3 = new StringBuilder();
foreach (String lol in Directory.GetFiles(@"mypath", "*.exe", SearchOption.AllDirectories);s)
{    
    lstResult.Add(Path.GetFileNameWithoutExtension(lol) + "," + Path.GetExtension(lol)+"," + Path.GetFullPath(lol);

    sb1.AppendLine(lol);
    sb2.AppendLine(Path.GetFileNameWithoutExtension(lol));
    sb3.AppendLine(Path.GetExtension(lol));
}

File.WriteAllLines(@"C:\BigB.csv", lstResult.ToArray());

textbox1.Text = sb1.ToString();
textbox2.Text = sb2.ToString();
textbox3.Text = sb3.ToString();