while(!String.IsNullOrEmpty(tempString = streamReader.ReadLine()))此循环仅迭代一次。任何帮助表示赞赏。完整方法:
public static ArrayList Load()
{
ArrayList vehicles = new ArrayList();
FileStream file = new FileStream(Constants.fileName, FileMode.OpenOrCreate);
StreamReader streamReader = new StreamReader(file);
String typeOfVehicle = " ";
String model = " ";
String manufactuer = " ";
Int32 year = 0;
Int32 vin = 0;
Double price = 0;
String purchaseDate = " ";
Int32 currentOdometerReading = 0;
Double sizeOfEngine = 0;
String typeOfMotorCycle = " ";
Int32 numOfDoors = 0;
String typeOfFuel = " ";
Double cargoCapacity = 0;
Double towingCapacity = 0;
String tempString = " ";
while (!String.IsNullOrEmpty(tempString = streamReader.ReadLine()))
{
String[] split = tempString.Split('~');
typeOfVehicle = split[0];
manufactuer = split[1];
model = split[2];
year = Convert.ToInt32(split[3]);
vin = Convert.ToInt32(split[4]);
price = Convert.ToDouble(split[5]);
purchaseDate = split[6];
currentOdometerReading = Convert.ToInt32(split[7]);
sizeOfEngine = Convert.ToDouble(split[8]);
if (typeOfVehicle == "Automobile")
{
numOfDoors = Convert.ToInt32(split[9]);
typeOfFuel = split[10];
Automobile car = new Automobile(manufactuer, model, year, vin, price, purchaseDate, currentOdometerReading, sizeOfEngine, numOfDoors, typeOfFuel);
VehicleCount.IncreaseCarCount();
vehicles.Add(car);
}
else if (typeOfVehicle == "Motorcycle")
{
typeOfMotorCycle = split[9];
Motorcycle bike = new Motorcycle(manufactuer, model, year, vin, price, purchaseDate, currentOdometerReading, sizeOfEngine, typeOfMotorCycle);
VehicleCount.IncreaseBikeCount();
vehicles.Add(bike);
}
else
{
cargoCapacity = Convert.ToDouble(split[9]);
towingCapacity = Convert.ToDouble(split[10]);
Truck truck = new Truck(manufactuer, model, year, vin, price, purchaseDate, currentOdometerReading, sizeOfEngine, cargoCapacity, towingCapacity);
VehicleCount.IncreaseTruckCount();
vehicles.Add(truck);
}
}
streamReader.Close();
return vehicles;
}
答案 0 :(得分:1)
请尝试以下。
while ((tempString = streamReader.ReadLine()) != null)
{
// ...
}
当前代码的问题是一旦遇到空行就会退出循环
(!String.IsNullOrEmpty(tempString = streamReader.ReadLine()))
答案 1 :(得分:0)
试试这个......
using (StreamReader streamReader = new StreamReader(file))
{
string tempString ;
while ((tempString = streamReader .ReadLine()) != null)
{
}
}