C#帮助将此代码从VB.NET转换为C#

C#帮助将此代码从VB.NET转换为C#,c#,vb.net,C#,Vb.net,任何帮助都将不胜感激,我正在尝试将下面的代码转换为C#,我从未使用过VB.NET,因此对我来说,ReDim是一个新的 谢谢 Dim inFile As System.IO.FileStream Dim binaryData() As Byte Dim strFileName As String strFileName = "C:\MyPicture.jpeg" inFile = New System.IO.FileStream(strFileName, System.IO.FileMode.

任何帮助都将不胜感激,我正在尝试将下面的代码转换为C#,我从未使用过VB.NET,因此对我来说,ReDim是一个新的

谢谢

Dim inFile As System.IO.FileStream
Dim binaryData() As Byte
Dim strFileName As String

strFileName = "C:\MyPicture.jpeg"

inFile = New System.IO.FileStream(strFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)

''//Retrive Data into a byte array variable
ReDim binaryData(inFile.Length)
Dim bytesRead As Long = inFile.Read(binaryData, 0, CInt(inFile.Length))
inFile.Close()

代码可以逐字转换,但有一种更简单的方法来实现这一点(从文件中读取所有字节),即


就我个人而言,我会将strFileName重命名为just
fileName
,因为在.NET代码中匈牙利符号是不受欢迎的。。。但那是另一回事

ReDim用于调整数组大小。(如果需要,您也可以保留内容。此代码不能做到这一点)

我认为ReDim语句只是用于初始化数组:

byte[] binaryData;

binaryData = new byte[inFile.Lenght];

ReDim重新分配阵列。大多数情况下,这是一种代码味道:一种症状,或者说是真正想要的是集合类型而不是数组。此代码应执行您想要的操作:

string FileName = @"C:\MyPicture.jpeg";
byte[] binaryData;
long bytesRead;

using (var inFile = new System.IO.FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read) )
{
    binaryData = new byte[inFile.Length];
    bytesRead = inFile.Read(binaryData, 0, (int)inFile.Length);
}
//I'm assuming you're actually doing something with each byte array here
最贴切的翻译是:

binaryData = new byte[inFile.Length];
由于尚未分配,或:

Array.Resize(ref binaryData,inFile.Length);
如果以前分配过。但是,代码本身是非常不安全的(您不应该假设
Read
读取所有请求的数据);一个更简单的方法是:

binaryData = File.ReadAllBytes(strFileName);

这很容易转换为C

但是有一个更好的方法来写这个

string fileName = @"C:\MyPicture.jpeg";
byte[] binaryData = File.ReadAllBytes(fileName);

这里有一个永久的解决方案,以防你以后需要再次这样做

下面是VB到C代码转换器的在线链接,反之亦然。一个是,另一个是

链接文本1:
LinkText2:

如果您要将大量VB.NET转换为C#,您可能需要签出。

注意:在旧版本的.NET中,将“var”替换为“byte[]”。@Brain:No,在C#3.0之前的编译器中,将var替换为byte[]。@Brian-您是指旧版本的C#;您仍然可以在.NET中使用“var”2@Brian-是的,为指出这一点干杯。我太习惯C#3.0了,我忘了在旧版本中不能使用var!使用var.@Joel的一个很好的例子——即使这有点异味;假设流读取的数据量与请求的数据量相同是不安全的;即使对于简单的情况,循环(检查读取返回)在技术上也是必要的。大多数流(包括FileStream)对此都很宽容——但不是全部。是的:修复了它,以便在using语句之后ByteRead仍在作用域中。
FileStream inFile;
byte[] binaryData;
string strFileName;

strFileName = @"C:\MyPicture.jpeg";

inFile = new System.IO.FileStream(strFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

binaryData = new byte[inFile.Length];
int bytesRead = inFile.Read(binaryData, 0, binaryData.Length);
inFile.Close();
string fileName = @"C:\MyPicture.jpeg";
byte[] binaryData = File.ReadAllBytes(fileName);