我正在尝试编写单元测试以确保该方法正在写入文本文件。我的方法写入文本文件MovieListTEST.txt
。我一直收到一个错误,说它无法访问该文件,因为它正被另一个进程使用。所以我尝试更改方法以接受一个参数来写入另一个文本文件public bool WriteMovieListToFile()
{
try
{
FileStream fs = new FileStream("MovieList.txt", FileMode.Append, FileAccess.Write);
StreamWriter textWriter = new StreamWriter(fs);
textWriter.WriteLine(movie.Title);
textWriter.WriteLine(movie.Genre);
textWriter.WriteLine(movie.Actor);
textWriter.WriteLine(movie.Year);
textWriter.Close();
return true;
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
return false;
}
}
,但我仍然无法弄明白。任何人都知道如何正确地做到这一点?
这是我写入文件的代码:
public bool WriteMovieListToFile(string fileLocation)
{
try
{
FileStream fs = new FileStream(fileLocation, FileMode.Append, FileAccess.Write);
StreamWriter textWriter = new StreamWriter(fs);
用param编辑:
/// <summary>
///A test for WriteMovieListToFile
///</summary>
[TestMethod()]
public void WriteMovieListToFileTest1()
{
Movie movie1 = new Movie("Title", "Genre", "Actor", "Year");
movieSystem.AddMovie(movie1);
movieSystem.WriteMovieListToFile("MovieListTEST.txt");
var fileText = File.ReadLines("MovieListTEST.txt");
Assert.IsTrue(fileText.ToString().Length > 1);
}
这是我的单元测试代码:
.carousel {
width: 800px;
}
/*Text over image*/
h2.header {
bottom: 0;
position: absolute;
text-align: center;
margin: 0;
width: 100%;
background-color: rgba(0,0,0,0.7);
padding: 35px 0px 35px 0px;
font-family: FeaturedItem;
}
.item {
position: relative;
width: 100%;
}
.item img {
display: block;
max-width:100%;
}
.item .overlay {
position: absolute;
top:0;
left:0;
width:380px;
height:100%;
color:white;
}
答案 0 :(得分:5)
只需将FileStream
括在using
块中,即可释放文件和内存。您可以借此机会对StreamWriter
:
public bool WriteMovieListToFile()
{
try
{
using (FileStream fs = new FileStream("MovieList.txt", FileMode.Append, FileAccess.Write))
using (StreamWriter textWriter = new StreamWriter(fs))
{
textWriter.WriteLine(movie.Title);
textWriter.WriteLine(movie.Genre);
textWriter.WriteLine(movie.Actor);
textWriter.WriteLine(movie.Year);
}
return true;
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
return false;
}
}
StreamWriter.Dispose()
与.Close()
的功能相同,因此使用此方法,您的代码也更清晰,更短。
顺便说一下,我将textWriter
重命名为streamWriter
,因此它与其类型一致。
答案 1 :(得分:1)
完成后,您需要关闭文件流。
public bool WriteMovieListToFile()
{
try
{
FileStream fs = new FileStream("MovieList.txt", FileMode.Append, FileAccess.Write);
StreamWriter textWriter = new StreamWriter(fs);
textWriter.WriteLine(movie.Title);
textWriter.WriteLine(movie.Genre);
textWriter.WriteLine(movie.Actor);
textWriter.WriteLine(movie.Year);
textWriter.Close();
fs.Dispose();
fs.Flush();
return true;
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
return false;
}
}