一開始的土法煉鋼寫法
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string filePath,Mon,Day,Temp;
private void button1_Click(object sender, EventArgs e)
{
getCSV();
}
public void getCSV()
{
filePath = Application.StartupPath + @"\test.txt";
WebClient wc = new WebClient();
try
{
using (FileStream fs = new FileStream(filePath, FileMode.Append))
{
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
for (int i = 2011; i <= 2011; i++)
{
for (int j = 6; j <= 6; j++)
{
int day;
if (DateTime.IsLeapYear(i) == true && j == 2)
{
day = 29;
}
else
{
if ((j == 4) || (j == 6) || (j == 9) || (j == 11))
{
day = 10;
}
else if (j == 2)
{
day = 28;
}
else
{
day = 31;
}
}
for (int k = 1; k <= day; k++)
{
if (j < 10 && k < 10)
{
Mon = "0" + j.ToString();
Day = "0" + k.ToString();
}
else if (j > 9 && k < 10)
{
Mon = j.ToString();
Day = "0" + k.ToString();
}
else if (j < 10 && k > 9)
{
Mon = "0" + j.ToString();
Day = k.ToString();
}
else
{
Mon = j.ToString();
Day = k.ToString();
}
sw.WriteLine(i.ToString() + Mon + Day);
Temp = i.ToString() + Mon + Day;
}
}
}
sw.Close();
}
fs.Close();
}
}
catch (IOException ex)
{
MessageBox.Show("錯誤訊息:" + ex.Message, "IOException例外");
}
}
}
}
使用內建的函數後
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string filePath,Mon,Day,Temp;
private void button1_Click(object sender, EventArgs e)
{
getCSV();
}
public void getCSV()
{
filePath = Application.StartupPath + @"\test.txt";
WebClient wc = new WebClient();
try
{
using (FileStream fs = new FileStream(filePath, FileMode.Append))
{
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
for (int i = 2011; i <= 2011; i++)
{
for (int j = 1; j <= 12; j++)
{
int day;
if (DateTime.IsLeapYear(i) == true && j == 2)
{
day = 29;
}
else
{
if ((j == 4) || (j == 6) || (j == 9) || (j == 11))
{
day = 10;
}
else if (j == 2)
{
day = 28;
}
else
{
day = 31;
}
}
for (int k = 1; k <= day; k++)
{
Mon = j.ToString().PadLeft(2, '0');
Day = k.ToString().PadLeft(2, '0');
Temp = i.ToString() + Mon + Day;
sw.WriteLine(Temp);
}
}
}
sw.Close();
}
fs.Close();
}
}
catch (IOException ex)
{
MessageBox.Show("錯誤訊息:" + ex.Message, "IOException例外");
}
}
}
}
用法:
ToString().PadLeft(2, '0');
ToString().PadRight(8, ‘0’);