SftpTests.cs 230 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494
  1. using System.Diagnostics;
  2. using Renci.SshNet.Common;
  3. using Renci.SshNet.IntegrationTests.Common;
  4. using Renci.SshNet.Sftp;
  5. namespace Renci.SshNet.IntegrationTests
  6. {
  7. // TODO: DeleteDirectory (fail + success
  8. // TODO: DeleteFile (fail + success
  9. // TODO: Delete (fail + success
  10. [TestClass]
  11. public class SftpTests : TestBase
  12. {
  13. private IConnectionInfoFactory _connectionInfoFactory;
  14. private IConnectionInfoFactory _adminConnectionInfoFactory;
  15. private IRemotePathTransformation _remotePathTransformation;
  16. [TestInitialize]
  17. public void SetUp()
  18. {
  19. _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
  20. _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
  21. _remotePathTransformation = RemotePathTransformation.ShellQuote;
  22. }
  23. [TestMethod]
  24. [DynamicData(nameof(GetSftpUploadFileFileStreamData), DynamicDataSourceType.Method)]
  25. public void Sftp_UploadFile_FileStream(int size)
  26. {
  27. var file = CreateTempFile(size);
  28. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  29. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  30. {
  31. client.Connect();
  32. var remoteFile = GenerateUniqueRemoteFileName();
  33. if (client.Exists(remoteFile))
  34. {
  35. client.Delete(remoteFile);
  36. }
  37. try
  38. {
  39. client.UploadFile(fs, remoteFile);
  40. using (var memoryStream = new MemoryStream(size))
  41. {
  42. DownloadFileRandomMethod(client, remoteFile, memoryStream);
  43. memoryStream.Position = 0;
  44. Assert.AreEqual(CreateFileHash(file), CreateHash(memoryStream));
  45. }
  46. }
  47. finally
  48. {
  49. if (client.Exists(remoteFile))
  50. {
  51. client.Delete(remoteFile);
  52. }
  53. }
  54. }
  55. }
  56. [TestMethod]
  57. public void Sftp_ConnectDisconnect_Serial()
  58. {
  59. const int iterations = 100;
  60. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  61. {
  62. for (var i = 1; i <= iterations; i++)
  63. {
  64. client.Connect();
  65. client.Disconnect();
  66. }
  67. }
  68. }
  69. [TestMethod]
  70. public void Sftp_ConnectDisconnect_Parallel()
  71. {
  72. const int iterations = 10;
  73. const int threads = 5;
  74. var startEvent = new ManualResetEvent(false);
  75. var tasks = Enumerable.Range(1, threads).Select(i =>
  76. {
  77. return Task.Factory.StartNew(() =>
  78. {
  79. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  80. {
  81. startEvent.WaitOne();
  82. for (var j = 0; j < iterations; j++)
  83. {
  84. client.Connect();
  85. client.Disconnect();
  86. }
  87. }
  88. });
  89. }).ToArray();
  90. startEvent.Set();
  91. Task.WaitAll(tasks);
  92. }
  93. [TestMethod]
  94. public void Sftp_BeginUploadFile()
  95. {
  96. const string content = "SftpBeginUploadFile";
  97. var expectedByteCount = (ulong)Encoding.ASCII.GetByteCount(content);
  98. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  99. {
  100. client.Connect();
  101. var remoteFile = GenerateUniqueRemoteFileName();
  102. if (client.Exists(remoteFile))
  103. {
  104. client.Delete(remoteFile);
  105. }
  106. try
  107. {
  108. using (var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(content)))
  109. {
  110. IAsyncResult asyncResultCallback = null;
  111. using var callbackCalled = new ManualResetEventSlim(false);
  112. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, ar =>
  113. {
  114. asyncResultCallback = ar;
  115. callbackCalled.Set();
  116. });
  117. Assert.IsTrue(asyncResult.AsyncWaitHandle.WaitOne(10000));
  118. // check async result
  119. var sftpUploadAsyncResult = asyncResult as SftpUploadAsyncResult;
  120. Assert.IsNotNull(sftpUploadAsyncResult);
  121. Assert.IsFalse(sftpUploadAsyncResult.IsUploadCanceled);
  122. Assert.IsTrue(sftpUploadAsyncResult.IsCompleted);
  123. Assert.IsFalse(sftpUploadAsyncResult.CompletedSynchronously);
  124. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResult.UploadedBytes);
  125. Assert.IsTrue(callbackCalled.Wait(10000));
  126. // check async result callback
  127. var sftpUploadAsyncResultCallback = asyncResultCallback as SftpUploadAsyncResult;
  128. Assert.IsNotNull(sftpUploadAsyncResultCallback);
  129. Assert.IsFalse(sftpUploadAsyncResultCallback.IsUploadCanceled);
  130. Assert.IsTrue(sftpUploadAsyncResultCallback.IsCompleted);
  131. Assert.IsFalse(sftpUploadAsyncResultCallback.CompletedSynchronously);
  132. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResultCallback.UploadedBytes);
  133. }
  134. // check uploaded file
  135. using (var memoryStream = new MemoryStream())
  136. {
  137. DownloadFileRandomMethod(client, remoteFile, memoryStream);
  138. memoryStream.Position = 0;
  139. var remoteContent = Encoding.ASCII.GetString(memoryStream.ToArray());
  140. Assert.AreEqual(content, remoteContent);
  141. }
  142. }
  143. finally
  144. {
  145. if (client.Exists(remoteFile))
  146. {
  147. client.Delete(remoteFile);
  148. }
  149. }
  150. }
  151. }
  152. [TestMethod]
  153. public void Sftp_Create_ExistingFile()
  154. {
  155. var encoding = Encoding.UTF8;
  156. var initialContent = "Gert & Ann & Lisa";
  157. var newContent1 = "Sofie";
  158. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  159. var newContent2 = "Lisa & Sofie";
  160. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  161. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  162. {
  163. client.Connect();
  164. var remoteFile = GenerateUniqueRemoteFileName();
  165. if (client.Exists(remoteFile))
  166. {
  167. client.DeleteFile(remoteFile);
  168. }
  169. try
  170. {
  171. client.WriteAllText(remoteFile, initialContent);
  172. #region Write less bytes than the current content, overwriting part of that content
  173. using (var fs = client.Create(remoteFile))
  174. using (var sw = new StreamWriter(fs, encoding))
  175. {
  176. sw.Write(newContent1);
  177. }
  178. var actualContent1 = client.ReadAllBytes(remoteFile);
  179. CollectionAssert.AreEqual(newContent1Bytes, actualContent1);
  180. #endregion Write less bytes than the current content, overwriting part of that content
  181. #region Write more bytes than the current content, overwriting and appending to that content
  182. using (var fs = client.Create(remoteFile))
  183. using (var sw = new StreamWriter(fs, encoding))
  184. {
  185. sw.Write(newContent2);
  186. }
  187. var actualContent2 = client.ReadAllBytes(remoteFile);
  188. CollectionAssert.AreEqual(newContent2Bytes, actualContent2);
  189. #endregion Write more bytes than the current content, overwriting and appending to that content
  190. }
  191. finally
  192. {
  193. if (client.Exists(remoteFile))
  194. {
  195. client.DeleteFile(remoteFile);
  196. }
  197. }
  198. }
  199. }
  200. [TestMethod]
  201. public void Sftp_Create_DirectoryDoesNotExist()
  202. {
  203. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  204. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  205. {
  206. client.Connect();
  207. if (client.Exists(remoteFile))
  208. {
  209. client.DeleteFile(remoteFile);
  210. }
  211. SftpFileStream fs = null;
  212. try
  213. {
  214. fs = client.Create(remoteFile);
  215. Assert.Fail();
  216. }
  217. catch (SftpPathNotFoundException ex)
  218. {
  219. Assert.IsNull(ex.InnerException);
  220. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  221. Assert.AreEqual(remoteFile, ex.Path);
  222. }
  223. finally
  224. {
  225. fs?.Dispose();
  226. if (client.Exists(remoteFile))
  227. {
  228. client.DeleteFile(remoteFile);
  229. }
  230. }
  231. }
  232. }
  233. [TestMethod]
  234. public void Sftp_Create_FileDoesNotExist()
  235. {
  236. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  237. {
  238. client.BufferSize = 512 * 1024;
  239. client.Connect();
  240. var remoteFile = GenerateUniqueRemoteFileName();
  241. if (client.Exists(remoteFile))
  242. {
  243. client.DeleteFile(remoteFile);
  244. }
  245. try
  246. {
  247. using (var imageStream = GetData("resources.issue #70.png"))
  248. {
  249. using (var fs = client.Create(remoteFile))
  250. {
  251. imageStream.CopyTo(fs);
  252. }
  253. using (var memoryStream = new MemoryStream())
  254. {
  255. DownloadFileRandomMethod(client, remoteFile, memoryStream);
  256. memoryStream.Position = 0;
  257. imageStream.Position = 0;
  258. Assert.AreEqual(CreateHash(imageStream), CreateHash(memoryStream));
  259. }
  260. }
  261. }
  262. finally
  263. {
  264. if (client.Exists(remoteFile))
  265. {
  266. client.DeleteFile(remoteFile);
  267. }
  268. }
  269. }
  270. }
  271. [TestMethod]
  272. public void Sftp_AppendAllLines_NoEncoding_ExistingFile()
  273. {
  274. var initialContent = "\u0100ert & Ann";
  275. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  276. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  277. Environment.NewLine;
  278. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  279. {
  280. client.Connect();
  281. var remoteFile = GenerateUniqueRemoteFileName();
  282. if (client.Exists(remoteFile))
  283. {
  284. client.DeleteFile(remoteFile);
  285. }
  286. try
  287. {
  288. client.WriteAllText(remoteFile, initialContent);
  289. client.AppendAllLines(remoteFile, linesToAppend);
  290. var text = client.ReadAllText(remoteFile);
  291. Assert.AreEqual(expectedContent, text);
  292. // ensure we didn't write an UTF-8 BOM
  293. using (var fs = client.OpenRead(remoteFile))
  294. {
  295. var firstByte = fs.ReadByte();
  296. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  297. }
  298. }
  299. finally
  300. {
  301. if (client.Exists(remoteFile))
  302. {
  303. client.DeleteFile(remoteFile);
  304. }
  305. }
  306. }
  307. }
  308. [TestMethod]
  309. public void Sftp_AppendAllLines_NoEncoding_DirectoryDoesNotExist()
  310. {
  311. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  312. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  313. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  314. {
  315. client.Connect();
  316. if (client.Exists(remoteFile))
  317. {
  318. client.DeleteFile(remoteFile);
  319. }
  320. try
  321. {
  322. client.AppendAllLines(remoteFile, linesToAppend);
  323. Assert.Fail();
  324. }
  325. catch (SftpPathNotFoundException ex)
  326. {
  327. Assert.IsNull(ex.InnerException);
  328. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  329. Assert.AreEqual(remoteFile, ex.Path);
  330. }
  331. finally
  332. {
  333. if (client.Exists(remoteFile))
  334. {
  335. client.DeleteFile(remoteFile);
  336. }
  337. }
  338. }
  339. }
  340. [TestMethod]
  341. public void Sftp_AppendAllLines_NoEncoding_FileDoesNotExist()
  342. {
  343. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  344. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  345. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  346. {
  347. client.Connect();
  348. var remoteFile = GenerateUniqueRemoteFileName();
  349. if (client.Exists(remoteFile))
  350. {
  351. client.DeleteFile(remoteFile);
  352. }
  353. try
  354. {
  355. client.AppendAllLines(remoteFile, linesToAppend);
  356. var text = client.ReadAllText(remoteFile);
  357. Assert.AreEqual(expectedContent, text);
  358. // ensure we didn't write an UTF-8 BOM
  359. using (var fs = client.OpenRead(remoteFile))
  360. {
  361. var firstByte = fs.ReadByte();
  362. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  363. }
  364. }
  365. finally
  366. {
  367. if (client.Exists(remoteFile))
  368. {
  369. client.DeleteFile(remoteFile);
  370. }
  371. }
  372. }
  373. }
  374. [TestMethod]
  375. public void Sftp_AppendAllText_NoEncoding_ExistingFile()
  376. {
  377. var initialContent = "\u0100ert & Ann";
  378. var contentToAppend = "Forever&\u0116ver";
  379. var expectedContent = initialContent + contentToAppend;
  380. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  381. {
  382. client.Connect();
  383. var remoteFile = GenerateUniqueRemoteFileName();
  384. if (client.Exists(remoteFile))
  385. {
  386. client.DeleteFile(remoteFile);
  387. }
  388. try
  389. {
  390. client.WriteAllText(remoteFile, initialContent);
  391. client.AppendAllText(remoteFile, contentToAppend);
  392. var text = client.ReadAllText(remoteFile);
  393. Assert.AreEqual(expectedContent, text);
  394. // ensure we didn't write an UTF-8 BOM
  395. using (var fs = client.OpenRead(remoteFile))
  396. {
  397. var firstByte = fs.ReadByte();
  398. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  399. }
  400. }
  401. finally
  402. {
  403. if (client.Exists(remoteFile))
  404. {
  405. client.DeleteFile(remoteFile);
  406. }
  407. }
  408. }
  409. }
  410. [TestMethod]
  411. public void Sftp_AppendAllText_NoEncoding_DirectoryDoesNotExist()
  412. {
  413. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  414. var contentToAppend = "Forever&\u0116ver";
  415. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  416. {
  417. client.Connect();
  418. if (client.Exists(remoteFile))
  419. {
  420. client.DeleteFile(remoteFile);
  421. }
  422. try
  423. {
  424. client.AppendAllText(remoteFile, contentToAppend);
  425. Assert.Fail();
  426. }
  427. catch (SftpPathNotFoundException ex)
  428. {
  429. Assert.IsNull(ex.InnerException);
  430. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  431. Assert.AreEqual(remoteFile, ex.Path);
  432. }
  433. finally
  434. {
  435. if (client.Exists(remoteFile))
  436. {
  437. client.DeleteFile(remoteFile);
  438. }
  439. }
  440. }
  441. }
  442. [TestMethod]
  443. public void Sftp_AppendAllText_NoEncoding_FileDoesNotExist()
  444. {
  445. var contentToAppend = "Forever&\u0116ver";
  446. var expectedContent = contentToAppend;
  447. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  448. {
  449. client.Connect();
  450. var remoteFile = GenerateUniqueRemoteFileName();
  451. if (client.Exists(remoteFile))
  452. {
  453. client.DeleteFile(remoteFile);
  454. }
  455. try
  456. {
  457. client.AppendAllText(remoteFile, contentToAppend);
  458. var text = client.ReadAllText(remoteFile);
  459. Assert.AreEqual(expectedContent, text);
  460. // ensure we didn't write an UTF-8 BOM
  461. using (var fs = client.OpenRead(remoteFile))
  462. {
  463. var firstByte = fs.ReadByte();
  464. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  465. }
  466. }
  467. finally
  468. {
  469. if (client.Exists(remoteFile))
  470. {
  471. client.DeleteFile(remoteFile);
  472. }
  473. }
  474. }
  475. }
  476. [TestMethod]
  477. public void Sftp_AppendText_NoEncoding_ExistingFile()
  478. {
  479. var initialContent = "\u0100ert & Ann";
  480. var contentToAppend = "Forever&\u0116ver";
  481. var expectedContent = initialContent + contentToAppend;
  482. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  483. {
  484. client.Connect();
  485. var remoteFile = GenerateUniqueRemoteFileName();
  486. if (client.Exists(remoteFile))
  487. {
  488. client.DeleteFile(remoteFile);
  489. }
  490. try
  491. {
  492. client.WriteAllText(remoteFile, initialContent);
  493. using (var sw = client.AppendText(remoteFile))
  494. {
  495. sw.Write(contentToAppend);
  496. }
  497. var text = client.ReadAllText(remoteFile);
  498. Assert.AreEqual(expectedContent, text);
  499. // ensure we didn't write an UTF-8 BOM
  500. using (var fs = client.OpenRead(remoteFile))
  501. {
  502. var firstByte = fs.ReadByte();
  503. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  504. }
  505. }
  506. finally
  507. {
  508. if (client.Exists(remoteFile))
  509. {
  510. client.DeleteFile(remoteFile);
  511. }
  512. }
  513. }
  514. }
  515. [TestMethod]
  516. public void Sftp_AppendText_NoEncoding_DirectoryDoesNotExist()
  517. {
  518. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  519. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  520. {
  521. client.Connect();
  522. if (client.Exists(remoteFile))
  523. {
  524. client.DeleteFile(remoteFile);
  525. }
  526. StreamWriter sw = null;
  527. try
  528. {
  529. sw = client.AppendText(remoteFile);
  530. Assert.Fail();
  531. }
  532. catch (SftpPathNotFoundException ex)
  533. {
  534. Assert.IsNull(ex.InnerException);
  535. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  536. Assert.AreEqual(remoteFile, ex.Path);
  537. }
  538. finally
  539. {
  540. sw?.Dispose();
  541. if (client.Exists(remoteFile))
  542. {
  543. client.DeleteFile(remoteFile);
  544. }
  545. }
  546. }
  547. }
  548. [TestMethod]
  549. public void Sftp_AppendText_NoEncoding_FileDoesNotExist()
  550. {
  551. var contentToAppend = "\u0100ert & Ann";
  552. var expectedContent = contentToAppend;
  553. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  554. {
  555. client.Connect();
  556. var remoteFile = GenerateUniqueRemoteFileName();
  557. if (client.Exists(remoteFile))
  558. {
  559. client.DeleteFile(remoteFile);
  560. }
  561. try
  562. {
  563. using (var sw = client.AppendText(remoteFile))
  564. {
  565. sw.Write(contentToAppend);
  566. }
  567. // ensure we didn't write an UTF-8 BOM
  568. using (var fs = client.OpenRead(remoteFile))
  569. {
  570. var firstByte = fs.ReadByte();
  571. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  572. }
  573. }
  574. finally
  575. {
  576. if (client.Exists(remoteFile))
  577. {
  578. client.DeleteFile(remoteFile);
  579. }
  580. }
  581. }
  582. }
  583. [TestMethod]
  584. public void Sftp_AppendAllLines_Encoding_ExistingFile()
  585. {
  586. var initialContent = "\u0100ert & Ann";
  587. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  588. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  589. Environment.NewLine;
  590. var encoding = GetRandomEncoding();
  591. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  592. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  593. {
  594. client.Connect();
  595. var remoteFile = GenerateUniqueRemoteFileName();
  596. if (client.Exists(remoteFile))
  597. {
  598. client.DeleteFile(remoteFile);
  599. }
  600. try
  601. {
  602. client.WriteAllText(remoteFile, initialContent, encoding);
  603. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  604. var text = client.ReadAllText(remoteFile, encoding);
  605. Assert.AreEqual(expectedContent, text);
  606. var actualBytes = client.ReadAllBytes(remoteFile);
  607. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  608. }
  609. finally
  610. {
  611. if (client.Exists(remoteFile))
  612. {
  613. client.DeleteFile(remoteFile);
  614. }
  615. }
  616. }
  617. }
  618. [TestMethod]
  619. public void Sftp_AppendAllLines_Encoding_DirectoryDoesNotExist()
  620. {
  621. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  622. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  623. var encoding = GetRandomEncoding();
  624. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  625. {
  626. client.Connect();
  627. if (client.Exists(remoteFile))
  628. {
  629. client.DeleteFile(remoteFile);
  630. }
  631. try
  632. {
  633. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  634. Assert.Fail();
  635. }
  636. catch (SftpPathNotFoundException ex)
  637. {
  638. Assert.IsNull(ex.InnerException);
  639. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  640. Assert.AreEqual(remoteFile, ex.Path);
  641. }
  642. finally
  643. {
  644. if (client.Exists(remoteFile))
  645. {
  646. client.DeleteFile(remoteFile);
  647. }
  648. }
  649. }
  650. }
  651. [TestMethod]
  652. public void Sftp_AppendAllLines_Encoding_FileDoesNotExist()
  653. {
  654. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  655. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  656. var encoding = GetRandomEncoding();
  657. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  658. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  659. {
  660. client.Connect();
  661. var remoteFile = GenerateUniqueRemoteFileName();
  662. if (client.Exists(remoteFile))
  663. {
  664. client.DeleteFile(remoteFile);
  665. }
  666. try
  667. {
  668. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  669. var text = client.ReadAllText(remoteFile, encoding);
  670. Assert.AreEqual(expectedContent, text);
  671. var actualBytes = client.ReadAllBytes(remoteFile);
  672. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  673. }
  674. finally
  675. {
  676. if (client.Exists(remoteFile))
  677. {
  678. client.DeleteFile(remoteFile);
  679. }
  680. }
  681. }
  682. }
  683. [TestMethod]
  684. public void Sftp_AppendAllText_Encoding_ExistingFile()
  685. {
  686. var initialContent = "\u0100ert & Ann";
  687. var contentToAppend = "Forever&\u0116ver";
  688. var expectedContent = initialContent + contentToAppend;
  689. var encoding = GetRandomEncoding();
  690. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  691. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  692. {
  693. client.Connect();
  694. var remoteFile = GenerateUniqueRemoteFileName();
  695. if (client.Exists(remoteFile))
  696. {
  697. client.DeleteFile(remoteFile);
  698. }
  699. try
  700. {
  701. client.WriteAllText(remoteFile, initialContent, encoding);
  702. client.AppendAllText(remoteFile, contentToAppend, encoding);
  703. var text = client.ReadAllText(remoteFile, encoding);
  704. Assert.AreEqual(expectedContent, text);
  705. var actualBytes = client.ReadAllBytes(remoteFile);
  706. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  707. }
  708. finally
  709. {
  710. if (client.Exists(remoteFile))
  711. {
  712. client.DeleteFile(remoteFile);
  713. }
  714. }
  715. }
  716. }
  717. [TestMethod]
  718. public void Sftp_AppendAllText_Encoding_DirectoryDoesNotExist()
  719. {
  720. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  721. const string contentToAppend = "Forever&\u0116ver";
  722. var encoding = GetRandomEncoding();
  723. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  724. {
  725. client.Connect();
  726. if (client.Exists(remoteFile))
  727. {
  728. client.DeleteFile(remoteFile);
  729. }
  730. try
  731. {
  732. client.AppendAllText(remoteFile, contentToAppend, encoding);
  733. Assert.Fail();
  734. }
  735. catch (SftpPathNotFoundException ex)
  736. {
  737. Assert.IsNull(ex.InnerException);
  738. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  739. Assert.AreEqual(remoteFile, ex.Path);
  740. }
  741. finally
  742. {
  743. if (client.Exists(remoteFile))
  744. {
  745. client.DeleteFile(remoteFile);
  746. }
  747. }
  748. }
  749. }
  750. [TestMethod]
  751. public void Sftp_AppendAllText_Encoding_FileDoesNotExist()
  752. {
  753. const string contentToAppend = "Forever&\u0116ver";
  754. var expectedContent = contentToAppend;
  755. var encoding = GetRandomEncoding();
  756. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  757. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  758. {
  759. client.Connect();
  760. var remoteFile = GenerateUniqueRemoteFileName();
  761. if (client.Exists(remoteFile))
  762. {
  763. client.DeleteFile(remoteFile);
  764. }
  765. try
  766. {
  767. client.AppendAllText(remoteFile, contentToAppend, encoding);
  768. var text = client.ReadAllText(remoteFile, encoding);
  769. Assert.AreEqual(expectedContent, text);
  770. var actualBytes = client.ReadAllBytes(remoteFile);
  771. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  772. }
  773. finally
  774. {
  775. if (client.Exists(remoteFile))
  776. {
  777. client.DeleteFile(remoteFile);
  778. }
  779. }
  780. }
  781. }
  782. [TestMethod]
  783. public void Sftp_AppendText_Encoding_ExistingFile()
  784. {
  785. const string initialContent = "\u0100ert & Ann";
  786. const string contentToAppend = "Forever&\u0116ver";
  787. var expectedContent = initialContent + contentToAppend;
  788. var encoding = GetRandomEncoding();
  789. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  790. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  791. {
  792. client.Connect();
  793. var remoteFile = GenerateUniqueRemoteFileName();
  794. if (client.Exists(remoteFile))
  795. {
  796. client.DeleteFile(remoteFile);
  797. }
  798. try
  799. {
  800. client.WriteAllText(remoteFile, initialContent, encoding);
  801. using (var sw = client.AppendText(remoteFile, encoding))
  802. {
  803. sw.Write(contentToAppend);
  804. }
  805. var text = client.ReadAllText(remoteFile, encoding);
  806. Assert.AreEqual(expectedContent, text);
  807. var actualBytes = client.ReadAllBytes(remoteFile);
  808. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  809. }
  810. finally
  811. {
  812. if (client.Exists(remoteFile))
  813. {
  814. client.DeleteFile(remoteFile);
  815. }
  816. }
  817. }
  818. }
  819. [TestMethod]
  820. public void Sftp_AppendText_Encoding_DirectoryDoesNotExist()
  821. {
  822. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  823. var encoding = GetRandomEncoding();
  824. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  825. {
  826. client.Connect();
  827. if (client.Exists(remoteFile))
  828. {
  829. client.DeleteFile(remoteFile);
  830. }
  831. StreamWriter sw = null;
  832. try
  833. {
  834. sw = client.AppendText(remoteFile, encoding);
  835. Assert.Fail();
  836. }
  837. catch (SftpPathNotFoundException ex)
  838. {
  839. Assert.IsNull(ex.InnerException);
  840. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  841. Assert.AreEqual(remoteFile, ex.Path);
  842. }
  843. finally
  844. {
  845. sw?.Dispose();
  846. if (client.Exists(remoteFile))
  847. {
  848. client.DeleteFile(remoteFile);
  849. }
  850. }
  851. }
  852. }
  853. [TestMethod]
  854. public void Sftp_AppendText_Encoding_FileDoesNotExist()
  855. {
  856. var encoding = GetRandomEncoding();
  857. const string contentToAppend = "\u0100ert & Ann";
  858. var expectedBytes = GetBytesWithPreamble(contentToAppend, encoding);
  859. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  860. {
  861. client.Connect();
  862. var remoteFile = GenerateUniqueRemoteFileName();
  863. if (client.Exists(remoteFile))
  864. {
  865. client.DeleteFile(remoteFile);
  866. }
  867. try
  868. {
  869. using (var sw = client.AppendText(remoteFile, encoding))
  870. {
  871. sw.Write(contentToAppend);
  872. }
  873. var actualBytes = client.ReadAllBytes(remoteFile);
  874. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  875. }
  876. finally
  877. {
  878. if (client.Exists(remoteFile))
  879. {
  880. client.DeleteFile(remoteFile);
  881. }
  882. }
  883. }
  884. }
  885. [TestMethod]
  886. public void Sftp_CreateText_NoEncoding_ExistingFile()
  887. {
  888. var encoding = new UTF8Encoding(false, true);
  889. const string initialContent = "\u0100ert & Ann";
  890. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  891. const string newContent = "\u0116ver";
  892. var newContentBytes = GetBytesWithPreamble(newContent, encoding);
  893. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  894. {
  895. client.Connect();
  896. var remoteFile = GenerateUniqueRemoteFileName();
  897. if (client.Exists(remoteFile))
  898. {
  899. client.DeleteFile(remoteFile);
  900. }
  901. try
  902. {
  903. client.WriteAllText(remoteFile, initialContent);
  904. Assert.AreEqual(initialContentBytes.Length, client.Get(remoteFile).Length);
  905. using (var sw = client.CreateText(remoteFile))
  906. {
  907. sw.Write(newContent);
  908. }
  909. // verify that the file was truncated
  910. Assert.AreEqual(newContentBytes.Length, client.Get(remoteFile).Length);
  911. var text = client.ReadAllText(remoteFile);
  912. Assert.AreEqual(newContent, text);
  913. var actualBytes = client.ReadAllBytes(remoteFile);
  914. CollectionAssert.AreEqual(newContentBytes, actualBytes);
  915. }
  916. finally
  917. {
  918. if (client.Exists(remoteFile))
  919. {
  920. client.DeleteFile(remoteFile);
  921. }
  922. }
  923. }
  924. }
  925. [TestMethod]
  926. public void Sftp_CreateText_NoEncoding_DirectoryDoesNotExist()
  927. {
  928. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  929. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  930. {
  931. client.Connect();
  932. if (client.Exists(remoteFile))
  933. {
  934. client.DeleteFile(remoteFile);
  935. }
  936. StreamWriter sw = null;
  937. try
  938. {
  939. sw = client.CreateText(remoteFile);
  940. Assert.Fail();
  941. }
  942. catch (SftpPathNotFoundException ex)
  943. {
  944. Assert.IsNull(ex.InnerException);
  945. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  946. Assert.AreEqual(remoteFile, ex.Path);
  947. }
  948. finally
  949. {
  950. sw?.Dispose();
  951. if (client.Exists(remoteFile))
  952. {
  953. client.DeleteFile(remoteFile);
  954. }
  955. }
  956. }
  957. }
  958. [TestMethod]
  959. public void Sftp_CreateText_NoEncoding_FileDoesNotExist()
  960. {
  961. var encoding = new UTF8Encoding(false, true);
  962. var initialContent = "\u0100ert & Ann";
  963. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  964. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  965. {
  966. client.Connect();
  967. var remoteFile = GenerateUniqueRemoteFileName();
  968. if (client.Exists(remoteFile))
  969. {
  970. client.DeleteFile(remoteFile);
  971. }
  972. try
  973. {
  974. using (client.CreateText(remoteFile))
  975. {
  976. }
  977. // verify that empty file was created
  978. Assert.IsTrue(client.Exists(remoteFile));
  979. var file = client.GetAttributes(remoteFile);
  980. Assert.AreEqual(0, file.Size);
  981. client.DeleteFile(remoteFile);
  982. using (var sw = client.CreateText(remoteFile))
  983. {
  984. sw.Write(initialContent);
  985. }
  986. // verify that content is written to file
  987. var text = client.ReadAllText(remoteFile);
  988. Assert.AreEqual(initialContent, text);
  989. var actualBytes = client.ReadAllBytes(remoteFile);
  990. CollectionAssert.AreEqual(initialContentBytes, actualBytes);
  991. }
  992. finally
  993. {
  994. if (client.Exists(remoteFile))
  995. {
  996. client.DeleteFile(remoteFile);
  997. }
  998. }
  999. }
  1000. }
  1001. [TestMethod]
  1002. public void Sftp_CreateText_Encoding_ExistingFile()
  1003. {
  1004. var encoding = GetRandomEncoding();
  1005. var initialContent = "\u0100ert & Ann";
  1006. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1007. var newContent = "\u0116ver";
  1008. var newContentBytes = GetBytesWithPreamble(newContent, encoding);
  1009. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1010. {
  1011. client.Connect();
  1012. var remoteFile = GenerateUniqueRemoteFileName();
  1013. if (client.Exists(remoteFile))
  1014. {
  1015. client.DeleteFile(remoteFile);
  1016. }
  1017. try
  1018. {
  1019. client.WriteAllText(remoteFile, initialContent, encoding);
  1020. Assert.AreEqual(initialContentBytes.Length, client.Get(remoteFile).Length);
  1021. using (var sw = client.CreateText(remoteFile, encoding))
  1022. {
  1023. sw.Write(newContent);
  1024. }
  1025. // verify that the file was truncated
  1026. Assert.AreEqual(newContentBytes.Length, client.Get(remoteFile).Length);
  1027. var text = client.ReadAllText(remoteFile);
  1028. Assert.AreEqual(newContent, text);
  1029. var actualBytes = client.ReadAllBytes(remoteFile);
  1030. CollectionAssert.AreEqual(newContentBytes, actualBytes);
  1031. }
  1032. finally
  1033. {
  1034. if (client.Exists(remoteFile))
  1035. {
  1036. client.DeleteFile(remoteFile);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. [TestMethod]
  1042. public void Sftp_CreateText_Encoding_DirectoryDoesNotExist()
  1043. {
  1044. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1045. var encoding = GetRandomEncoding();
  1046. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1047. {
  1048. client.Connect();
  1049. if (client.Exists(remoteFile))
  1050. {
  1051. client.DeleteFile(remoteFile);
  1052. }
  1053. StreamWriter sw = null;
  1054. try
  1055. {
  1056. sw = client.CreateText(remoteFile, encoding);
  1057. Assert.Fail();
  1058. }
  1059. catch (SftpPathNotFoundException ex)
  1060. {
  1061. Assert.IsNull(ex.InnerException);
  1062. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  1063. Assert.AreEqual(remoteFile, ex.Path);
  1064. }
  1065. finally
  1066. {
  1067. sw?.Dispose();
  1068. if (client.Exists(remoteFile))
  1069. {
  1070. client.DeleteFile(remoteFile);
  1071. }
  1072. }
  1073. }
  1074. }
  1075. [TestMethod]
  1076. public void Sftp_CreateText_Encoding_FileDoesNotExist()
  1077. {
  1078. var encoding = GetRandomEncoding();
  1079. var initialContent = "\u0100ert & Ann";
  1080. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1081. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1082. {
  1083. client.Connect();
  1084. var remoteFile = GenerateUniqueRemoteFileName();
  1085. if (client.Exists(remoteFile))
  1086. {
  1087. client.DeleteFile(remoteFile);
  1088. }
  1089. try
  1090. {
  1091. using (client.CreateText(remoteFile, encoding))
  1092. {
  1093. }
  1094. // verify that file containing only preamble was created
  1095. Assert.IsTrue(client.Exists(remoteFile));
  1096. var file = client.GetAttributes(remoteFile);
  1097. Assert.AreEqual(encoding.GetPreamble().Length, file.Size);
  1098. client.DeleteFile(remoteFile);
  1099. using (var sw = client.CreateText(remoteFile, encoding))
  1100. {
  1101. sw.Write(initialContent);
  1102. }
  1103. // verify that content is written to file
  1104. var text = client.ReadAllText(remoteFile, encoding);
  1105. Assert.AreEqual(initialContent, text);
  1106. var actualBytes = client.ReadAllBytes(remoteFile);
  1107. CollectionAssert.AreEqual(initialContentBytes, actualBytes);
  1108. }
  1109. finally
  1110. {
  1111. if (client.Exists(remoteFile))
  1112. {
  1113. client.DeleteFile(remoteFile);
  1114. }
  1115. }
  1116. }
  1117. }
  1118. [TestMethod]
  1119. public void Sftp_DownloadFile_FileDoesNotExist()
  1120. {
  1121. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1122. {
  1123. client.Connect();
  1124. var remoteFile = GenerateUniqueRemoteFileName();
  1125. if (client.Exists(remoteFile))
  1126. {
  1127. client.DeleteFile(remoteFile);
  1128. }
  1129. using (var ms = new MemoryStream())
  1130. {
  1131. try
  1132. {
  1133. client.DownloadFile(remoteFile, ms);
  1134. Assert.Fail();
  1135. }
  1136. catch (SftpPathNotFoundException ex)
  1137. {
  1138. Assert.IsNull(ex.InnerException);
  1139. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  1140. Assert.AreEqual(remoteFile, ex.Path);
  1141. // ensure file was not created by us
  1142. Assert.IsFalse(client.Exists(remoteFile));
  1143. }
  1144. finally
  1145. {
  1146. if (client.Exists(remoteFile))
  1147. {
  1148. client.DeleteFile(remoteFile);
  1149. }
  1150. }
  1151. }
  1152. }
  1153. }
  1154. [TestMethod]
  1155. public void Sftp_ReadAllBytes_FileDoesNotExist()
  1156. {
  1157. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1158. {
  1159. client.Connect();
  1160. var remoteFile = GenerateUniqueRemoteFileName();
  1161. if (client.Exists(remoteFile))
  1162. {
  1163. client.DeleteFile(remoteFile);
  1164. }
  1165. try
  1166. {
  1167. client.ReadAllBytes(remoteFile);
  1168. Assert.Fail();
  1169. }
  1170. catch (SftpPathNotFoundException ex)
  1171. {
  1172. Assert.IsNull(ex.InnerException);
  1173. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  1174. Assert.AreEqual(remoteFile, ex.Path);
  1175. // ensure file was not created by us
  1176. Assert.IsFalse(client.Exists(remoteFile));
  1177. }
  1178. finally
  1179. {
  1180. if (client.Exists(remoteFile))
  1181. {
  1182. client.DeleteFile(remoteFile);
  1183. }
  1184. }
  1185. }
  1186. }
  1187. [TestMethod]
  1188. public void Sftp_ReadAllLines_NoEncoding_ExistingFile()
  1189. {
  1190. var encoding = new UTF8Encoding(false, true);
  1191. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1192. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1193. encoding);
  1194. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1195. {
  1196. client.Connect();
  1197. var remoteFile = GenerateUniqueRemoteFileName();
  1198. if (client.Exists(remoteFile))
  1199. {
  1200. client.DeleteFile(remoteFile);
  1201. }
  1202. try
  1203. {
  1204. using (var sw = client.AppendText(remoteFile))
  1205. {
  1206. for (var i = 0; i < lines.Length; i++)
  1207. {
  1208. sw.WriteLine(lines[i]);
  1209. }
  1210. }
  1211. var actualLines = client.ReadAllLines(remoteFile);
  1212. Assert.IsNotNull(actualLines);
  1213. CollectionAssert.AreEqual(lines, actualLines);
  1214. var actualBytes = client.ReadAllBytes(remoteFile);
  1215. CollectionAssert.AreEqual(linesBytes, actualBytes);
  1216. }
  1217. finally
  1218. {
  1219. if (client.Exists(remoteFile))
  1220. {
  1221. client.DeleteFile(remoteFile);
  1222. }
  1223. }
  1224. }
  1225. }
  1226. [TestMethod]
  1227. public void Sftp_ReadAllLines_NoEncoding_FileDoesNotExist()
  1228. {
  1229. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1230. {
  1231. client.Connect();
  1232. var remoteFile = GenerateUniqueRemoteFileName();
  1233. if (client.Exists(remoteFile))
  1234. {
  1235. client.DeleteFile(remoteFile);
  1236. }
  1237. try
  1238. {
  1239. client.ReadAllLines(remoteFile);
  1240. Assert.Fail();
  1241. }
  1242. catch (SftpPathNotFoundException ex)
  1243. {
  1244. Assert.IsNull(ex.InnerException);
  1245. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  1246. Assert.AreEqual(remoteFile, ex.Path);
  1247. // ensure file was not created by us
  1248. Assert.IsFalse(client.Exists(remoteFile));
  1249. }
  1250. finally
  1251. {
  1252. if (client.Exists(remoteFile))
  1253. {
  1254. client.DeleteFile(remoteFile);
  1255. }
  1256. }
  1257. }
  1258. }
  1259. [TestMethod]
  1260. public void Sftp_ReadAllLines_Encoding_ExistingFile()
  1261. {
  1262. var encoding = GetRandomEncoding();
  1263. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1264. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1265. encoding);
  1266. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1267. {
  1268. client.Connect();
  1269. var remoteFile = GenerateUniqueRemoteFileName();
  1270. if (client.Exists(remoteFile))
  1271. {
  1272. client.DeleteFile(remoteFile);
  1273. }
  1274. try
  1275. {
  1276. using (var sw = client.AppendText(remoteFile, encoding))
  1277. {
  1278. for (var i = 0; i < lines.Length; i++)
  1279. {
  1280. sw.WriteLine(lines[i]);
  1281. }
  1282. }
  1283. var actualLines = client.ReadAllLines(remoteFile, encoding);
  1284. Assert.IsNotNull(actualLines);
  1285. CollectionAssert.AreEqual(lines, actualLines);
  1286. var actualBytes = client.ReadAllBytes(remoteFile);
  1287. CollectionAssert.AreEqual(linesBytes, actualBytes);
  1288. }
  1289. finally
  1290. {
  1291. if (client.Exists(remoteFile))
  1292. {
  1293. client.DeleteFile(remoteFile);
  1294. }
  1295. }
  1296. }
  1297. }
  1298. [TestMethod]
  1299. public void Sftp_ReadAllLines_Encoding_FileDoesNotExist()
  1300. {
  1301. var encoding = GetRandomEncoding();
  1302. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1303. {
  1304. client.Connect();
  1305. var remoteFile = GenerateUniqueRemoteFileName();
  1306. if (client.Exists(remoteFile))
  1307. {
  1308. client.DeleteFile(remoteFile);
  1309. }
  1310. try
  1311. {
  1312. client.ReadAllLines(remoteFile, encoding);
  1313. Assert.Fail();
  1314. }
  1315. catch (SftpPathNotFoundException ex)
  1316. {
  1317. Assert.IsNull(ex.InnerException);
  1318. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  1319. Assert.AreEqual(remoteFile, ex.Path);
  1320. // ensure file was not created by us
  1321. Assert.IsFalse(client.Exists(remoteFile));
  1322. }
  1323. finally
  1324. {
  1325. if (client.Exists(remoteFile))
  1326. {
  1327. client.DeleteFile(remoteFile);
  1328. }
  1329. }
  1330. }
  1331. }
  1332. [TestMethod]
  1333. public void Sftp_ReadAllText_NoEncoding_ExistingFile()
  1334. {
  1335. var encoding = new UTF8Encoding(false, true);
  1336. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1337. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1338. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1339. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1340. {
  1341. client.Connect();
  1342. var remoteFile = GenerateUniqueRemoteFileName();
  1343. if (client.Exists(remoteFile))
  1344. {
  1345. client.DeleteFile(remoteFile);
  1346. }
  1347. try
  1348. {
  1349. using (var sw = client.AppendText(remoteFile))
  1350. {
  1351. for (var i = 0; i < lines.Length; i++)
  1352. {
  1353. sw.WriteLine(lines[i]);
  1354. }
  1355. }
  1356. var actualText = client.ReadAllText(remoteFile);
  1357. Assert.AreEqual(expectedText, actualText);
  1358. var actualBytes = client.ReadAllBytes(remoteFile);
  1359. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  1360. }
  1361. finally
  1362. {
  1363. if (client.Exists(remoteFile))
  1364. {
  1365. client.DeleteFile(remoteFile);
  1366. }
  1367. }
  1368. }
  1369. }
  1370. [TestMethod]
  1371. public void Sftp_ReadAllText_NoEncoding_FileDoesNotExist()
  1372. {
  1373. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1374. {
  1375. client.Connect();
  1376. var remoteFile = GenerateUniqueRemoteFileName();
  1377. if (client.Exists(remoteFile))
  1378. {
  1379. client.DeleteFile(remoteFile);
  1380. }
  1381. try
  1382. {
  1383. client.ReadAllText(remoteFile);
  1384. Assert.Fail();
  1385. }
  1386. catch (SftpPathNotFoundException ex)
  1387. {
  1388. Assert.IsNull(ex.InnerException);
  1389. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  1390. Assert.AreEqual(remoteFile, ex.Path);
  1391. // ensure file was not created by us
  1392. Assert.IsFalse(client.Exists(remoteFile));
  1393. }
  1394. finally
  1395. {
  1396. if (client.Exists(remoteFile))
  1397. {
  1398. client.DeleteFile(remoteFile);
  1399. }
  1400. }
  1401. }
  1402. }
  1403. [TestMethod]
  1404. public void Sftp_ReadAllText_Encoding_ExistingFile()
  1405. {
  1406. var encoding = GetRandomEncoding();
  1407. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1408. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1409. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1410. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1411. {
  1412. client.Connect();
  1413. var remoteFile = GenerateUniqueRemoteFileName();
  1414. if (client.Exists(remoteFile))
  1415. {
  1416. client.DeleteFile(remoteFile);
  1417. }
  1418. try
  1419. {
  1420. using (var sw = client.AppendText(remoteFile, encoding))
  1421. {
  1422. for (var i = 0; i < lines.Length; i++)
  1423. {
  1424. sw.WriteLine(lines[i]);
  1425. }
  1426. }
  1427. var actualText = client.ReadAllText(remoteFile, encoding);
  1428. Assert.AreEqual(expectedText, actualText);
  1429. var actualBytes = client.ReadAllBytes(remoteFile);
  1430. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  1431. }
  1432. finally
  1433. {
  1434. if (client.Exists(remoteFile))
  1435. {
  1436. client.DeleteFile(remoteFile);
  1437. }
  1438. }
  1439. }
  1440. }
  1441. [TestMethod]
  1442. public void Sftp_ReadAllText_Encoding_FileDoesNotExist()
  1443. {
  1444. var encoding = GetRandomEncoding();
  1445. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1446. {
  1447. client.Connect();
  1448. var remoteFile = GenerateUniqueRemoteFileName();
  1449. if (client.Exists(remoteFile))
  1450. {
  1451. client.DeleteFile(remoteFile);
  1452. }
  1453. try
  1454. {
  1455. client.ReadAllText(remoteFile, encoding);
  1456. Assert.Fail();
  1457. }
  1458. catch (SftpPathNotFoundException ex)
  1459. {
  1460. Assert.IsNull(ex.InnerException);
  1461. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  1462. Assert.AreEqual(remoteFile, ex.Path);
  1463. // ensure file was not created by us
  1464. Assert.IsFalse(client.Exists(remoteFile));
  1465. }
  1466. finally
  1467. {
  1468. if (client.Exists(remoteFile))
  1469. {
  1470. client.DeleteFile(remoteFile);
  1471. }
  1472. }
  1473. }
  1474. }
  1475. [TestMethod]
  1476. public void Sftp_ReadLines_NoEncoding_ExistingFile()
  1477. {
  1478. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1479. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1480. {
  1481. client.Connect();
  1482. var remoteFile = GenerateUniqueRemoteFileName();
  1483. if (client.Exists(remoteFile))
  1484. {
  1485. client.DeleteFile(remoteFile);
  1486. }
  1487. try
  1488. {
  1489. using (var sw = client.AppendText(remoteFile))
  1490. {
  1491. for (var i = 0; i < lines.Length; i++)
  1492. {
  1493. sw.WriteLine(lines[i]);
  1494. }
  1495. }
  1496. var actualLines = client.ReadLines(remoteFile);
  1497. Assert.IsNotNull(actualLines);
  1498. // These two lines together test double enumeration.
  1499. Assert.AreEqual(lines[0], actualLines.First());
  1500. CollectionAssert.AreEqual(lines, actualLines.ToArray());
  1501. }
  1502. finally
  1503. {
  1504. if (client.Exists(remoteFile))
  1505. {
  1506. client.DeleteFile(remoteFile);
  1507. }
  1508. }
  1509. }
  1510. }
  1511. [TestMethod]
  1512. [DataRow(false)]
  1513. [DataRow(true)]
  1514. public void Sftp_ReadLines_FileDoesNotExist(bool encoding)
  1515. {
  1516. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1517. {
  1518. client.Connect();
  1519. var remoteFile = GenerateUniqueRemoteFileName();
  1520. if (client.Exists(remoteFile))
  1521. {
  1522. client.DeleteFile(remoteFile);
  1523. }
  1524. // This exception should bubble up immediately
  1525. var nullEx = encoding
  1526. ? Assert.Throws<ArgumentNullException>(() => client.ReadLines(null, GetRandomEncoding()))
  1527. : Assert.Throws<ArgumentNullException>(() => client.ReadLines(null));
  1528. Assert.AreEqual("path", nullEx.ParamName);
  1529. try
  1530. {
  1531. var ex = Assert.ThrowsExactly<SftpPathNotFoundException>(() =>
  1532. {
  1533. // The PathNotFound exception is permitted to bubble up only upon
  1534. // enumerating.
  1535. var lines = encoding
  1536. ? client.ReadLines(remoteFile, GetRandomEncoding())
  1537. : client.ReadLines(remoteFile);
  1538. using var enumerator = lines.GetEnumerator();
  1539. _ = enumerator.MoveNext();
  1540. });
  1541. Assert.IsNull(ex.InnerException);
  1542. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  1543. Assert.AreEqual(remoteFile, ex.Path);
  1544. // ensure file was not created by us
  1545. Assert.IsFalse(client.Exists(remoteFile));
  1546. }
  1547. finally
  1548. {
  1549. if (client.Exists(remoteFile))
  1550. {
  1551. client.DeleteFile(remoteFile);
  1552. }
  1553. }
  1554. }
  1555. }
  1556. [TestMethod]
  1557. public void Sftp_ReadLines_Encoding_ExistingFile()
  1558. {
  1559. var encoding = GetRandomEncoding();
  1560. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1561. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1562. {
  1563. client.Connect();
  1564. var remoteFile = GenerateUniqueRemoteFileName();
  1565. if (client.Exists(remoteFile))
  1566. {
  1567. client.DeleteFile(remoteFile);
  1568. }
  1569. try
  1570. {
  1571. using (var sw = client.AppendText(remoteFile, encoding))
  1572. {
  1573. for (var i = 0; i < lines.Length; i++)
  1574. {
  1575. sw.WriteLine(lines[i]);
  1576. }
  1577. }
  1578. var actualLines = client.ReadLines(remoteFile, encoding);
  1579. Assert.IsNotNull(actualLines);
  1580. // These two lines together test double enumeration.
  1581. Assert.AreEqual(lines[0], actualLines.First());
  1582. CollectionAssert.AreEqual(lines, actualLines.ToArray());
  1583. }
  1584. finally
  1585. {
  1586. if (client.Exists(remoteFile))
  1587. {
  1588. client.DeleteFile(remoteFile);
  1589. }
  1590. }
  1591. }
  1592. }
  1593. [TestMethod]
  1594. public void Sftp_WriteAllBytes_DirectoryDoesNotExist()
  1595. {
  1596. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1597. var content = GenerateRandom(size: 5);
  1598. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1599. {
  1600. client.Connect();
  1601. if (client.Exists(remoteFile))
  1602. {
  1603. client.DeleteFile(remoteFile);
  1604. }
  1605. try
  1606. {
  1607. client.WriteAllBytes(remoteFile, content);
  1608. Assert.Fail();
  1609. }
  1610. catch (SftpPathNotFoundException ex)
  1611. {
  1612. Assert.IsNull(ex.InnerException);
  1613. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  1614. Assert.AreEqual(remoteFile, ex.Path);
  1615. }
  1616. finally
  1617. {
  1618. if (client.Exists(remoteFile))
  1619. {
  1620. client.DeleteFile(remoteFile);
  1621. }
  1622. }
  1623. }
  1624. }
  1625. [TestMethod]
  1626. public void Sftp_WriteAllBytes_ExistingFile()
  1627. {
  1628. var initialContent = GenerateRandom(size: 13);
  1629. var newContent1 = GenerateRandom(size: 5);
  1630. var newContent2 = GenerateRandom(size: 50000);
  1631. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1632. {
  1633. client.Connect();
  1634. var remoteFile = GenerateUniqueRemoteFileName();
  1635. if (client.Exists(remoteFile))
  1636. {
  1637. client.DeleteFile(remoteFile);
  1638. }
  1639. try
  1640. {
  1641. using (var fs = client.Create(remoteFile))
  1642. {
  1643. fs.Write(initialContent, offset: 0, initialContent.Length);
  1644. }
  1645. #region Write less bytes than the current content, overwriting that content
  1646. client.WriteAllBytes(remoteFile, newContent1);
  1647. var actualContent1 = client.ReadAllBytes(remoteFile);
  1648. CollectionAssert.AreEqual(newContent1, actualContent1);
  1649. #endregion
  1650. #region Write more bytes than the current content, overwriting and appending to that content
  1651. client.WriteAllBytes(remoteFile, newContent2);
  1652. var actualContent2 = client.ReadAllBytes(remoteFile);
  1653. CollectionAssert.AreEqual(newContent2, actualContent2);
  1654. #endregion
  1655. }
  1656. finally
  1657. {
  1658. if (client.Exists(remoteFile))
  1659. {
  1660. client.DeleteFile(remoteFile);
  1661. }
  1662. }
  1663. }
  1664. }
  1665. [TestMethod]
  1666. public void Sftp_WriteAllBytes_FileDoesNotExist()
  1667. {
  1668. var content = GenerateRandom(size: 13);
  1669. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1670. {
  1671. client.Connect();
  1672. var remoteFile = GenerateUniqueRemoteFileName();
  1673. if (client.Exists(remoteFile))
  1674. {
  1675. client.DeleteFile(remoteFile);
  1676. }
  1677. try
  1678. {
  1679. client.WriteAllBytes(remoteFile, content);
  1680. var actualContent1 = client.ReadAllBytes(remoteFile);
  1681. CollectionAssert.AreEqual(content, actualContent1);
  1682. }
  1683. finally
  1684. {
  1685. if (client.Exists(remoteFile))
  1686. {
  1687. client.DeleteFile(remoteFile);
  1688. }
  1689. }
  1690. }
  1691. }
  1692. [TestMethod]
  1693. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_DirectoryDoesNotExist()
  1694. {
  1695. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1696. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1697. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1698. {
  1699. client.Connect();
  1700. if (client.Exists(remoteFile))
  1701. {
  1702. client.DeleteFile(remoteFile);
  1703. }
  1704. try
  1705. {
  1706. client.WriteAllLines(remoteFile, linesToWrite);
  1707. Assert.Fail();
  1708. }
  1709. catch (SftpPathNotFoundException ex)
  1710. {
  1711. Assert.IsNull(ex.InnerException);
  1712. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  1713. Assert.AreEqual(remoteFile, ex.Path);
  1714. }
  1715. finally
  1716. {
  1717. if (client.Exists(remoteFile))
  1718. {
  1719. client.DeleteFile(remoteFile);
  1720. }
  1721. }
  1722. }
  1723. }
  1724. [TestMethod]
  1725. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_ExistingFile()
  1726. {
  1727. var encoding = new UTF8Encoding(false, true);
  1728. var initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1729. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1730. var linesToWrite1Bytes =
  1731. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1732. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1733. var linesToWrite2Bytes =
  1734. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1735. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1736. {
  1737. client.Connect();
  1738. var remoteFile = GenerateUniqueRemoteFileName();
  1739. if (client.Exists(remoteFile))
  1740. {
  1741. client.DeleteFile(remoteFile);
  1742. }
  1743. try
  1744. {
  1745. // create initial content
  1746. client.WriteAllText(remoteFile, initialContent);
  1747. #region Write less bytes than the current content, overwriting that content
  1748. client.WriteAllLines(remoteFile, linesToWrite1);
  1749. var actualBytes = client.ReadAllBytes(remoteFile);
  1750. CollectionAssert.AreEqual(linesToWrite1Bytes, actualBytes);
  1751. #endregion
  1752. #region Write more bytes than the current content, overwriting and appending to that content
  1753. client.WriteAllLines(remoteFile, linesToWrite2);
  1754. actualBytes = client.ReadAllBytes(remoteFile);
  1755. CollectionAssert.AreEqual(linesToWrite2Bytes, actualBytes);
  1756. #endregion Write more bytes than the current content, overwriting and appending to that content
  1757. }
  1758. finally
  1759. {
  1760. if (client.Exists(remoteFile))
  1761. {
  1762. client.DeleteFile(remoteFile);
  1763. }
  1764. }
  1765. }
  1766. }
  1767. [TestMethod]
  1768. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_FileDoesNotExist()
  1769. {
  1770. var encoding = new UTF8Encoding(false, true);
  1771. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1772. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1773. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1774. {
  1775. client.Connect();
  1776. var remoteFile = GenerateUniqueRemoteFileName();
  1777. if (client.Exists(remoteFile))
  1778. {
  1779. client.DeleteFile(remoteFile);
  1780. }
  1781. try
  1782. {
  1783. client.WriteAllLines(remoteFile, linesToWrite);
  1784. var actualBytes = client.ReadAllBytes(remoteFile);
  1785. CollectionAssert.AreEqual(linesToWriteBytes, actualBytes);
  1786. }
  1787. finally
  1788. {
  1789. if (client.Exists(remoteFile))
  1790. {
  1791. client.DeleteFile(remoteFile);
  1792. }
  1793. }
  1794. }
  1795. }
  1796. [TestMethod]
  1797. public void Sftp_WriteAllLines_IEnumerable_Encoding_DirectoryDoesNotExist()
  1798. {
  1799. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1800. var encoding = GetRandomEncoding();
  1801. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1802. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1803. {
  1804. client.Connect();
  1805. if (client.Exists(remoteFile))
  1806. {
  1807. client.DeleteFile(remoteFile);
  1808. }
  1809. try
  1810. {
  1811. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1812. Assert.Fail();
  1813. }
  1814. catch (SftpPathNotFoundException ex)
  1815. {
  1816. Assert.IsNull(ex.InnerException);
  1817. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  1818. Assert.AreEqual(remoteFile, ex.Path);
  1819. }
  1820. finally
  1821. {
  1822. if (client.Exists(remoteFile))
  1823. {
  1824. client.DeleteFile(remoteFile);
  1825. }
  1826. }
  1827. }
  1828. }
  1829. [TestMethod]
  1830. public void Sftp_WriteAllLines_IEnumerable_Encoding_ExistingFile()
  1831. {
  1832. var encoding = GetRandomEncoding();
  1833. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1834. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1835. var linesToWrite1Bytes =
  1836. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1837. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1838. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1839. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1840. {
  1841. client.Connect();
  1842. var remoteFile = GenerateUniqueRemoteFileName();
  1843. if (client.Exists(remoteFile))
  1844. {
  1845. client.DeleteFile(remoteFile);
  1846. }
  1847. try
  1848. {
  1849. // create initial content
  1850. client.WriteAllText(remoteFile, initialContent, encoding);
  1851. #region Write less bytes than the current content, overwriting that content
  1852. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  1853. var actualBytes = client.ReadAllBytes(remoteFile);
  1854. CollectionAssert.AreEqual(linesToWrite1Bytes, actualBytes);
  1855. #endregion
  1856. #region Write more bytes than the current content, overwriting and appending to that content
  1857. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  1858. actualBytes = client.ReadAllBytes(remoteFile);
  1859. CollectionAssert.AreEqual(linesToWrite2Bytes, actualBytes);
  1860. #endregion Write more bytes than the current content, overwriting and appending to that content
  1861. }
  1862. finally
  1863. {
  1864. if (client.Exists(remoteFile))
  1865. {
  1866. client.DeleteFile(remoteFile);
  1867. }
  1868. }
  1869. }
  1870. }
  1871. [TestMethod]
  1872. public void Sftp_WriteAllLines_IEnumerable_Encoding_FileDoesNotExist()
  1873. {
  1874. var encoding = GetRandomEncoding();
  1875. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1876. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1877. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1878. {
  1879. client.Connect();
  1880. var remoteFile = GenerateUniqueRemoteFileName();
  1881. if (client.Exists(remoteFile))
  1882. {
  1883. client.DeleteFile(remoteFile);
  1884. }
  1885. try
  1886. {
  1887. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1888. var actualBytes = client.ReadAllBytes(remoteFile);
  1889. CollectionAssert.AreEqual(linesToWriteBytes, actualBytes);
  1890. }
  1891. finally
  1892. {
  1893. if (client.Exists(remoteFile))
  1894. {
  1895. client.DeleteFile(remoteFile);
  1896. }
  1897. }
  1898. }
  1899. }
  1900. [TestMethod]
  1901. public void Sftp_WriteAllLines_Array_NoEncoding_DirectoryDoesNotExist()
  1902. {
  1903. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1904. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1905. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1906. {
  1907. client.Connect();
  1908. if (client.Exists(remoteFile))
  1909. {
  1910. client.DeleteFile(remoteFile);
  1911. }
  1912. try
  1913. {
  1914. client.WriteAllLines(remoteFile, linesToWrite);
  1915. Assert.Fail();
  1916. }
  1917. catch (SftpPathNotFoundException ex)
  1918. {
  1919. Assert.IsNull(ex.InnerException);
  1920. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  1921. Assert.AreEqual(remoteFile, ex.Path);
  1922. }
  1923. finally
  1924. {
  1925. if (client.Exists(remoteFile))
  1926. {
  1927. client.DeleteFile(remoteFile);
  1928. }
  1929. }
  1930. }
  1931. }
  1932. [TestMethod]
  1933. public void Sftp_WriteAllLines_Array_NoEncoding_ExistingFile()
  1934. {
  1935. var encoding = new UTF8Encoding(false, true);
  1936. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1937. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1938. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1939. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1940. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1941. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1942. {
  1943. client.Connect();
  1944. var remoteFile = GenerateUniqueRemoteFileName();
  1945. if (client.Exists(remoteFile))
  1946. {
  1947. client.DeleteFile(remoteFile);
  1948. }
  1949. try
  1950. {
  1951. // create initial content
  1952. client.WriteAllText(remoteFile, initialContent);
  1953. #region Write less bytes than the current content, overwriting that content
  1954. client.WriteAllLines(remoteFile, linesToWrite1);
  1955. var actualBytes = client.ReadAllBytes(remoteFile);
  1956. CollectionAssert.AreEqual(linesToWrite1Bytes, actualBytes);
  1957. #endregion
  1958. #region Write more bytes than the current content, overwriting and appending to that content
  1959. client.WriteAllLines(remoteFile, linesToWrite2);
  1960. actualBytes = client.ReadAllBytes(remoteFile);
  1961. CollectionAssert.AreEqual(linesToWrite2Bytes, actualBytes);
  1962. #endregion Write more bytes than the current content, overwriting and appending to that content
  1963. }
  1964. finally
  1965. {
  1966. if (client.Exists(remoteFile))
  1967. {
  1968. client.DeleteFile(remoteFile);
  1969. }
  1970. }
  1971. }
  1972. }
  1973. [TestMethod]
  1974. public void Sftp_WriteAllLines_Array_NoEncoding_FileDoesNotExist()
  1975. {
  1976. var encoding = new UTF8Encoding(false, true);
  1977. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1978. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1979. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1980. {
  1981. client.Connect();
  1982. var remoteFile = GenerateUniqueRemoteFileName();
  1983. if (client.Exists(remoteFile))
  1984. {
  1985. client.DeleteFile(remoteFile);
  1986. }
  1987. try
  1988. {
  1989. client.WriteAllLines(remoteFile, linesToWrite);
  1990. var actualBytes = client.ReadAllBytes(remoteFile);
  1991. CollectionAssert.AreEqual(linesToWriteBytes, actualBytes);
  1992. }
  1993. finally
  1994. {
  1995. if (client.Exists(remoteFile))
  1996. {
  1997. client.DeleteFile(remoteFile);
  1998. }
  1999. }
  2000. }
  2001. }
  2002. [TestMethod]
  2003. public void Sftp_WriteAllLines_Array_Encoding_DirectoryDoesNotExist()
  2004. {
  2005. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2006. var encoding = GetRandomEncoding();
  2007. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  2008. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2009. {
  2010. client.Connect();
  2011. if (client.Exists(remoteFile))
  2012. {
  2013. client.DeleteFile(remoteFile);
  2014. }
  2015. try
  2016. {
  2017. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2018. Assert.Fail();
  2019. }
  2020. catch (SftpPathNotFoundException ex)
  2021. {
  2022. Assert.IsNull(ex.InnerException);
  2023. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  2024. Assert.AreEqual(remoteFile, ex.Path);
  2025. }
  2026. finally
  2027. {
  2028. if (client.Exists(remoteFile))
  2029. {
  2030. client.DeleteFile(remoteFile);
  2031. }
  2032. }
  2033. }
  2034. }
  2035. [TestMethod]
  2036. public void Sftp_WriteAllLines_Array_Encoding_ExistingFile()
  2037. {
  2038. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2039. var encoding = GetRandomEncoding();
  2040. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2041. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2042. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2043. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2044. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2045. {
  2046. client.Connect();
  2047. var remoteFile = GenerateUniqueRemoteFileName();
  2048. if (client.Exists(remoteFile))
  2049. {
  2050. client.DeleteFile(remoteFile);
  2051. }
  2052. try
  2053. {
  2054. // create initial content
  2055. client.WriteAllText(remoteFile, initialContent, encoding);
  2056. #region Write less bytes than the current content, overwriting that content
  2057. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2058. var actualBytes = client.ReadAllBytes(remoteFile);
  2059. CollectionAssert.AreEqual(linesToWrite1Bytes, actualBytes);
  2060. #endregion
  2061. #region Write more bytes than the current content, overwriting and appending to that content
  2062. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2063. actualBytes = client.ReadAllBytes(remoteFile);
  2064. CollectionAssert.AreEqual(linesToWrite2Bytes, actualBytes);
  2065. #endregion
  2066. }
  2067. finally
  2068. {
  2069. if (client.Exists(remoteFile))
  2070. {
  2071. client.DeleteFile(remoteFile);
  2072. }
  2073. }
  2074. }
  2075. }
  2076. [TestMethod]
  2077. public void Sftp_WriteAllLines_Array_Encoding_FileDoesNotExist()
  2078. {
  2079. var encoding = GetRandomEncoding();
  2080. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2081. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2082. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2083. {
  2084. client.Connect();
  2085. var remoteFile = GenerateUniqueRemoteFileName();
  2086. if (client.Exists(remoteFile))
  2087. {
  2088. client.DeleteFile(remoteFile);
  2089. }
  2090. try
  2091. {
  2092. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2093. var actualBytes = client.ReadAllBytes(remoteFile);
  2094. CollectionAssert.AreEqual(linesToWriteBytes, actualBytes);
  2095. }
  2096. finally
  2097. {
  2098. if (client.Exists(remoteFile))
  2099. {
  2100. client.DeleteFile(remoteFile);
  2101. }
  2102. }
  2103. }
  2104. }
  2105. [TestMethod]
  2106. public void Sftp_WriteAllText_NoEncoding_DirectoryDoesNotExist()
  2107. {
  2108. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2109. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2110. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2111. {
  2112. client.Connect();
  2113. if (client.Exists(remoteFile))
  2114. {
  2115. client.DeleteFile(remoteFile);
  2116. }
  2117. try
  2118. {
  2119. client.WriteAllText(remoteFile, initialContent);
  2120. Assert.Fail();
  2121. }
  2122. catch (SftpPathNotFoundException ex)
  2123. {
  2124. Assert.IsNull(ex.InnerException);
  2125. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  2126. Assert.AreEqual(remoteFile, ex.Path);
  2127. }
  2128. finally
  2129. {
  2130. if (client.Exists(remoteFile))
  2131. {
  2132. client.DeleteFile(remoteFile);
  2133. }
  2134. }
  2135. }
  2136. }
  2137. [TestMethod]
  2138. public void Sftp_WriteAllText_NoEncoding_ExistingFile()
  2139. {
  2140. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2141. const string newContent1 = "For\u0116ver & Ever";
  2142. var encoding = new UTF8Encoding(false, true);
  2143. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2144. var newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2145. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2146. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2147. {
  2148. client.Connect();
  2149. var remoteFile = GenerateUniqueRemoteFileName();
  2150. if (client.Exists(remoteFile))
  2151. {
  2152. client.DeleteFile(remoteFile);
  2153. }
  2154. try
  2155. {
  2156. client.WriteAllText(remoteFile, initialContent);
  2157. #region Write less bytes than the current content, overwriting that content
  2158. client.WriteAllText(remoteFile, newContent1);
  2159. var actualBytes = client.ReadAllBytes(remoteFile);
  2160. CollectionAssert.AreEqual(newContent1Bytes, actualBytes);
  2161. #endregion
  2162. #region Write more bytes than the current content, overwriting and appending to that content
  2163. client.WriteAllText(remoteFile, newContent2);
  2164. actualBytes = client.ReadAllBytes(remoteFile);
  2165. CollectionAssert.AreEqual(newContent2Bytes, actualBytes);
  2166. #endregion Write more bytes than the current content, overwriting and appending to that content
  2167. }
  2168. finally
  2169. {
  2170. if (client.Exists(remoteFile))
  2171. {
  2172. client.DeleteFile(remoteFile);
  2173. }
  2174. }
  2175. }
  2176. }
  2177. [TestMethod]
  2178. public void Sftp_WriteAllText_NoEncoding_FileDoesNotExist()
  2179. {
  2180. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2181. var encoding = new UTF8Encoding(false, true);
  2182. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2183. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2184. {
  2185. client.Connect();
  2186. var remoteFile = GenerateUniqueRemoteFileName();
  2187. if (client.Exists(remoteFile))
  2188. {
  2189. client.DeleteFile(remoteFile);
  2190. }
  2191. try
  2192. {
  2193. client.WriteAllText(remoteFile, initialContent);
  2194. var actualBytes = client.ReadAllBytes(remoteFile);
  2195. CollectionAssert.AreEqual(initialContentBytes, actualBytes);
  2196. }
  2197. finally
  2198. {
  2199. if (client.Exists(remoteFile))
  2200. {
  2201. client.DeleteFile(remoteFile);
  2202. }
  2203. }
  2204. }
  2205. }
  2206. [TestMethod]
  2207. public void Sftp_WriteAllText_Encoding_DirectoryDoesNotExist()
  2208. {
  2209. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2210. var encoding = GetRandomEncoding();
  2211. const string content = "For\u0116ver & Ever";
  2212. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2213. {
  2214. client.Connect();
  2215. if (client.Exists(remoteFile))
  2216. {
  2217. client.DeleteFile(remoteFile);
  2218. }
  2219. try
  2220. {
  2221. client.WriteAllText(remoteFile, content, encoding);
  2222. Assert.Fail();
  2223. }
  2224. catch (SftpPathNotFoundException ex)
  2225. {
  2226. Assert.IsNull(ex.InnerException);
  2227. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  2228. Assert.AreEqual(remoteFile, ex.Path);
  2229. }
  2230. finally
  2231. {
  2232. if (client.Exists(remoteFile))
  2233. {
  2234. client.DeleteFile(remoteFile);
  2235. }
  2236. }
  2237. }
  2238. }
  2239. [TestMethod]
  2240. public void Sftp_WriteAllText_Encoding_ExistingFile()
  2241. {
  2242. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2243. const string newContent1 = "For\u0116ver & Ever";
  2244. const string newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2245. var encoding = GetRandomEncoding();
  2246. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2247. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2248. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2249. {
  2250. client.Connect();
  2251. var remoteFile = GenerateUniqueRemoteFileName();
  2252. if (client.Exists(remoteFile))
  2253. {
  2254. client.DeleteFile(remoteFile);
  2255. }
  2256. try
  2257. {
  2258. client.WriteAllText(remoteFile, initialContent, encoding);
  2259. #region Write less bytes than the current content, overwriting that content
  2260. client.WriteAllText(remoteFile, newContent1, encoding);
  2261. var actualBytes = client.ReadAllBytes(remoteFile);
  2262. CollectionAssert.AreEqual(newContent1Bytes, actualBytes);
  2263. #endregion
  2264. #region Write more bytes than the current content, overwriting and appending to that content
  2265. client.WriteAllText(remoteFile, newContent2, encoding);
  2266. actualBytes = client.ReadAllBytes(remoteFile);
  2267. CollectionAssert.AreEqual(newContent2Bytes, actualBytes);
  2268. #endregion Write more bytes than the current content, overwriting and appending to that content
  2269. }
  2270. finally
  2271. {
  2272. if (client.Exists(remoteFile))
  2273. {
  2274. client.DeleteFile(remoteFile);
  2275. }
  2276. }
  2277. }
  2278. }
  2279. [TestMethod]
  2280. public void Sftp_WriteAllText_Encoding_FileDoesNotExist()
  2281. {
  2282. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2283. var encoding = GetRandomEncoding();
  2284. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2285. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2286. {
  2287. client.Connect();
  2288. var remoteFile = GenerateUniqueRemoteFileName();
  2289. if (client.Exists(remoteFile))
  2290. {
  2291. client.DeleteFile(remoteFile);
  2292. }
  2293. try
  2294. {
  2295. client.WriteAllText(remoteFile, initialContent, encoding);
  2296. var actualBytes = client.ReadAllBytes(remoteFile);
  2297. CollectionAssert.AreEqual(initialContentBytes, actualBytes);
  2298. }
  2299. finally
  2300. {
  2301. if (client.Exists(remoteFile))
  2302. {
  2303. client.DeleteFile(remoteFile);
  2304. }
  2305. }
  2306. }
  2307. }
  2308. [TestMethod]
  2309. public void Sftp_BeginDownloadFile_FileDoesNotExist()
  2310. {
  2311. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2312. {
  2313. client.Connect();
  2314. var remoteFile = GenerateUniqueRemoteFileName();
  2315. if (client.Exists(remoteFile))
  2316. {
  2317. client.DeleteFile(remoteFile);
  2318. }
  2319. try
  2320. {
  2321. using (var ms = new MemoryStream())
  2322. {
  2323. var asyncResult = client.BeginDownloadFile(remoteFile, ms);
  2324. try
  2325. {
  2326. client.EndDownloadFile(asyncResult);
  2327. Assert.Fail();
  2328. }
  2329. catch (SftpPathNotFoundException ex)
  2330. {
  2331. Assert.IsNull(ex.InnerException);
  2332. Assert.AreEqual($"No such file. Path: '{remoteFile}'.", ex.Message);
  2333. Assert.AreEqual(remoteFile, ex.Path);
  2334. // ensure file was not created by us
  2335. Assert.IsFalse(client.Exists(remoteFile));
  2336. }
  2337. }
  2338. }
  2339. finally
  2340. {
  2341. if (client.Exists(remoteFile))
  2342. {
  2343. client.DeleteFile(remoteFile);
  2344. }
  2345. }
  2346. }
  2347. }
  2348. [TestMethod]
  2349. public void Sftp_BeginListDirectory_DirectoryDoesNotExist()
  2350. {
  2351. const string remoteDirectory = "/home/sshnet/test123";
  2352. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2353. {
  2354. client.Connect();
  2355. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2356. {
  2357. command.Execute();
  2358. }
  2359. }
  2360. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2361. {
  2362. client.Connect();
  2363. var asyncResult = client.BeginListDirectory(remoteDirectory, null, null);
  2364. try
  2365. {
  2366. client.EndListDirectory(asyncResult);
  2367. Assert.Fail();
  2368. }
  2369. catch (SftpPathNotFoundException ex)
  2370. {
  2371. Assert.IsNull(ex.InnerException);
  2372. Assert.AreEqual($"No such file. Path: '{remoteDirectory}'.", ex.Message);
  2373. Assert.AreEqual(remoteDirectory, ex.Path);
  2374. // ensure directory was not created by us
  2375. Assert.IsFalse(client.Exists(remoteDirectory));
  2376. }
  2377. }
  2378. }
  2379. [TestMethod]
  2380. public void Sftp_BeginUploadFile_InputAndPath_DirectoryDoesNotExist()
  2381. {
  2382. const int size = 50 * 1024 * 1024;
  2383. const string remoteDirectory = "/home/sshnet/test123";
  2384. const string remoteFile = remoteDirectory + "/test";
  2385. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2386. {
  2387. client.Connect();
  2388. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2389. {
  2390. command.Execute();
  2391. }
  2392. }
  2393. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2394. {
  2395. client.Connect();
  2396. var memoryStream = CreateMemoryStream(size);
  2397. memoryStream.Position = 0;
  2398. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile);
  2399. try
  2400. {
  2401. client.EndUploadFile(asyncResult);
  2402. Assert.Fail();
  2403. }
  2404. catch (SftpPathNotFoundException)
  2405. {
  2406. }
  2407. }
  2408. }
  2409. [TestMethod]
  2410. public void Sftp_BeginUploadFile_InputAndPath_FileDoesNotExist()
  2411. {
  2412. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2413. {
  2414. client.Connect();
  2415. var remoteFile = GenerateUniqueRemoteFileName();
  2416. if (client.Exists(remoteFile))
  2417. {
  2418. client.DeleteFile(remoteFile);
  2419. }
  2420. try
  2421. {
  2422. var uploadMemoryStream = new MemoryStream();
  2423. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2424. sw.Write("Gert & Ann");
  2425. sw.Flush();
  2426. uploadMemoryStream.Position = 0;
  2427. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2428. client.EndUploadFile(asyncResult);
  2429. using (var downloadMemoryStream = new MemoryStream())
  2430. {
  2431. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2432. downloadMemoryStream.Position = 0;
  2433. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2434. {
  2435. var content = sr.ReadToEnd();
  2436. Assert.AreEqual("Gert & Ann", content);
  2437. }
  2438. }
  2439. }
  2440. finally
  2441. {
  2442. if (client.Exists(remoteFile))
  2443. {
  2444. client.DeleteFile(remoteFile);
  2445. }
  2446. }
  2447. }
  2448. }
  2449. [TestMethod]
  2450. public void Sftp_BeginUploadFile_InputAndPath_ExistingFile()
  2451. {
  2452. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2453. {
  2454. client.Connect();
  2455. var remoteFile = GenerateUniqueRemoteFileName();
  2456. if (client.Exists(remoteFile))
  2457. {
  2458. client.DeleteFile(remoteFile);
  2459. }
  2460. try
  2461. {
  2462. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2463. var uploadMemoryStream = new MemoryStream();
  2464. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2465. sw.Write("Ann & Gert");
  2466. sw.Flush();
  2467. uploadMemoryStream.Position = 0;
  2468. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2469. client.EndUploadFile(asyncResult);
  2470. using (var downloadMemoryStream = new MemoryStream())
  2471. {
  2472. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2473. downloadMemoryStream.Position = 0;
  2474. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2475. {
  2476. var content = sr.ReadToEnd();
  2477. Assert.AreEqual("Ann & Gert", content);
  2478. }
  2479. }
  2480. }
  2481. finally
  2482. {
  2483. if (client.Exists(remoteFile))
  2484. {
  2485. client.DeleteFile(remoteFile);
  2486. }
  2487. }
  2488. }
  2489. }
  2490. [TestMethod]
  2491. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_DirectoryDoesNotExist()
  2492. {
  2493. const int size = 50 * 1024 * 1024;
  2494. const string remoteDirectory = "/home/sshnet/test123";
  2495. const string remoteFile = remoteDirectory + "/test";
  2496. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2497. {
  2498. client.Connect();
  2499. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2500. {
  2501. command.Execute();
  2502. }
  2503. }
  2504. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2505. {
  2506. client.Connect();
  2507. var memoryStream = CreateMemoryStream(size);
  2508. memoryStream.Position = 0;
  2509. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, false, null, null);
  2510. try
  2511. {
  2512. client.EndUploadFile(asyncResult);
  2513. Assert.Fail();
  2514. }
  2515. catch (SftpPathNotFoundException)
  2516. {
  2517. }
  2518. }
  2519. }
  2520. [TestMethod]
  2521. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_FileDoesNotExist()
  2522. {
  2523. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2524. {
  2525. client.Connect();
  2526. var remoteFile = GenerateUniqueRemoteFileName();
  2527. if (client.Exists(remoteFile))
  2528. {
  2529. client.DeleteFile(remoteFile);
  2530. }
  2531. try
  2532. {
  2533. using (var uploadMemoryStream = new MemoryStream())
  2534. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2535. {
  2536. sw.Write("Gert & Ann");
  2537. sw.Flush();
  2538. uploadMemoryStream.Position = 0;
  2539. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2540. client.EndUploadFile(asyncResult);
  2541. }
  2542. using (var downloadMemoryStream = new MemoryStream())
  2543. {
  2544. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2545. downloadMemoryStream.Position = 0;
  2546. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2547. {
  2548. var content = sr.ReadToEnd();
  2549. Assert.AreEqual("Gert & Ann", content);
  2550. }
  2551. }
  2552. }
  2553. finally
  2554. {
  2555. if (client.Exists(remoteFile))
  2556. {
  2557. client.DeleteFile(remoteFile);
  2558. }
  2559. }
  2560. }
  2561. }
  2562. [TestMethod]
  2563. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_ExistingFile()
  2564. {
  2565. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2566. {
  2567. client.Connect();
  2568. var remoteFile = GenerateUniqueRemoteFileName();
  2569. if (client.Exists(remoteFile))
  2570. {
  2571. client.DeleteFile(remoteFile);
  2572. }
  2573. try
  2574. {
  2575. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2576. var uploadMemoryStream = new MemoryStream();
  2577. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2578. sw.Write("Ann & Gert");
  2579. sw.Flush();
  2580. uploadMemoryStream.Position = 0;
  2581. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2582. var ex = Assert.Throws<SftpException>(() => client.EndUploadFile(asyncResult));
  2583. Assert.AreEqual(StatusCode.Failure, ex.StatusCode);
  2584. }
  2585. finally
  2586. {
  2587. if (client.Exists(remoteFile))
  2588. {
  2589. client.DeleteFile(remoteFile);
  2590. }
  2591. }
  2592. }
  2593. }
  2594. [TestMethod]
  2595. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_DirectoryDoesNotExist()
  2596. {
  2597. const int size = 50 * 1024 * 1024;
  2598. const string remoteDirectory = "/home/sshnet/test123";
  2599. const string remoteFile = remoteDirectory + "/test";
  2600. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2601. {
  2602. client.Connect();
  2603. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2604. {
  2605. command.Execute();
  2606. }
  2607. }
  2608. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2609. {
  2610. client.Connect();
  2611. var memoryStream = CreateMemoryStream(size);
  2612. memoryStream.Position = 0;
  2613. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, true, null, null);
  2614. try
  2615. {
  2616. client.EndUploadFile(asyncResult);
  2617. Assert.Fail();
  2618. }
  2619. catch (SftpPathNotFoundException)
  2620. {
  2621. }
  2622. }
  2623. }
  2624. [TestMethod]
  2625. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_FileDoesNotExist()
  2626. {
  2627. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2628. {
  2629. client.Connect();
  2630. var remoteFile = GenerateUniqueRemoteFileName();
  2631. if (client.Exists(remoteFile))
  2632. {
  2633. client.DeleteFile(remoteFile);
  2634. }
  2635. try
  2636. {
  2637. using (var uploadMemoryStream = new MemoryStream())
  2638. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2639. {
  2640. sw.Write("Gert & Ann");
  2641. sw.Flush();
  2642. uploadMemoryStream.Position = 0;
  2643. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2644. client.EndUploadFile(asyncResult);
  2645. }
  2646. using (var downloadMemoryStream = new MemoryStream())
  2647. {
  2648. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2649. downloadMemoryStream.Position = 0;
  2650. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2651. {
  2652. var content = sr.ReadToEnd();
  2653. Assert.AreEqual("Gert & Ann", content);
  2654. }
  2655. }
  2656. }
  2657. finally
  2658. {
  2659. if (client.Exists(remoteFile))
  2660. {
  2661. client.DeleteFile(remoteFile);
  2662. }
  2663. }
  2664. }
  2665. }
  2666. [TestMethod]
  2667. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_ExistingFile()
  2668. {
  2669. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2670. {
  2671. client.Connect();
  2672. var remoteFile = GenerateUniqueRemoteFileName();
  2673. if (client.Exists(remoteFile))
  2674. {
  2675. client.DeleteFile(remoteFile);
  2676. }
  2677. try
  2678. {
  2679. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2680. using (var uploadMemoryStream = new MemoryStream())
  2681. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2682. {
  2683. sw.Write("Ann & Gert");
  2684. sw.Flush();
  2685. uploadMemoryStream.Position = 0;
  2686. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2687. client.EndUploadFile(asyncResult);
  2688. }
  2689. using (var downloadMemoryStream = new MemoryStream())
  2690. {
  2691. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2692. downloadMemoryStream.Position = 0;
  2693. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2694. {
  2695. var content = sr.ReadToEnd();
  2696. Assert.AreEqual("Ann & Gert", content);
  2697. }
  2698. }
  2699. }
  2700. finally
  2701. {
  2702. if (client.Exists(remoteFile))
  2703. {
  2704. client.DeleteFile(remoteFile);
  2705. }
  2706. }
  2707. }
  2708. }
  2709. [TestMethod]
  2710. public void Sftp_UploadAndDownloadBigFile()
  2711. {
  2712. const int size = 50 * 1024 * 1024;
  2713. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2714. {
  2715. client.Connect();
  2716. var remoteFile = GenerateUniqueRemoteFileName();
  2717. if (client.Exists(remoteFile))
  2718. {
  2719. client.Delete(remoteFile);
  2720. }
  2721. try
  2722. {
  2723. var memoryStream = CreateMemoryStream(size);
  2724. memoryStream.Position = 0;
  2725. var expectedHash = CreateHash(memoryStream);
  2726. memoryStream.Position = 0;
  2727. client.UploadFile(memoryStream, remoteFile);
  2728. memoryStream.SetLength(0);
  2729. var stopwatch = new Stopwatch();
  2730. stopwatch.Start();
  2731. client.DownloadFile(remoteFile, memoryStream);
  2732. stopwatch.Stop();
  2733. Assert.AreEqual(size, memoryStream.Length);
  2734. memoryStream.Position = 0;
  2735. var actualHash = CreateHash(memoryStream);
  2736. Assert.AreEqual(expectedHash, actualHash);
  2737. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  2738. Console.WriteLine(@"Transfer speed: {0:N2} KB/s",
  2739. CalculateTransferSpeed(memoryStream.Length, stopwatch.ElapsedMilliseconds));
  2740. }
  2741. finally
  2742. {
  2743. if (client.Exists(remoteFile))
  2744. {
  2745. client.Delete(remoteFile);
  2746. }
  2747. }
  2748. }
  2749. }
  2750. /// <summary>
  2751. /// Issue 1672
  2752. /// </summary>
  2753. [TestMethod]
  2754. public void Sftp_CurrentWorkingDirectory()
  2755. {
  2756. const string homeDirectory = "/home/sshnet";
  2757. const string otherDirectory = homeDirectory + "/dir";
  2758. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2759. {
  2760. client.Connect();
  2761. if (client.Exists(otherDirectory))
  2762. {
  2763. client.DeleteDirectory(otherDirectory);
  2764. }
  2765. try
  2766. {
  2767. client.CreateDirectory(otherDirectory);
  2768. client.ChangeDirectory(otherDirectory);
  2769. using (var s = CreateStreamWithContent("A"))
  2770. {
  2771. client.UploadFile(s, "a.txt");
  2772. }
  2773. using (var s = new MemoryStream())
  2774. {
  2775. client.DownloadFile("a.txt", s);
  2776. s.Position = 0;
  2777. var content = Encoding.ASCII.GetString(s.ToArray());
  2778. Assert.AreEqual("A", content);
  2779. }
  2780. Assert.IsTrue(client.Exists(otherDirectory + "/a.txt"));
  2781. client.DeleteFile("a.txt");
  2782. Assert.IsFalse(client.Exists(otherDirectory + "/a.txt"));
  2783. client.DeleteDirectory(".");
  2784. Assert.IsFalse(client.Exists(otherDirectory));
  2785. }
  2786. finally
  2787. {
  2788. if (client.Exists(otherDirectory))
  2789. {
  2790. client.DeleteDirectory(otherDirectory);
  2791. }
  2792. }
  2793. }
  2794. }
  2795. [TestMethod]
  2796. public void Sftp_Exists()
  2797. {
  2798. const string remoteHome = "/home/sshnet";
  2799. #region Setup
  2800. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2801. {
  2802. client.Connect();
  2803. #region Clean-up
  2804. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  2805. {
  2806. command.Execute();
  2807. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2808. }
  2809. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  2810. {
  2811. command.Execute();
  2812. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2813. }
  2814. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  2815. )
  2816. {
  2817. command.Execute();
  2818. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2819. }
  2820. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  2821. {
  2822. command.Execute();
  2823. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2824. }
  2825. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  2826. {
  2827. command.Execute();
  2828. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2829. }
  2830. #endregion Clean-up
  2831. #region Setup
  2832. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  2833. {
  2834. command.Execute();
  2835. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2836. }
  2837. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  2838. {
  2839. command.Execute();
  2840. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2841. }
  2842. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  2843. {
  2844. command.Execute();
  2845. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2846. }
  2847. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  2848. {
  2849. command.Execute();
  2850. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2851. }
  2852. #endregion Setup
  2853. }
  2854. #endregion Setup
  2855. #region Assert
  2856. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2857. {
  2858. client.Connect();
  2859. Assert.IsFalse(client.Exists(remoteHome + "/DoesNotExist"));
  2860. Assert.IsTrue(client.Exists(remoteHome + "/file.exists"));
  2861. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.file.exists"));
  2862. Assert.IsTrue(client.Exists(remoteHome + "/directory.exists"));
  2863. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.directory.exists"));
  2864. }
  2865. #endregion Assert
  2866. #region Teardown
  2867. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2868. {
  2869. client.Connect();
  2870. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  2871. {
  2872. command.Execute();
  2873. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2874. }
  2875. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  2876. {
  2877. command.Execute();
  2878. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2879. }
  2880. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  2881. {
  2882. command.Execute();
  2883. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2884. }
  2885. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  2886. {
  2887. command.Execute();
  2888. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2889. }
  2890. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  2891. {
  2892. command.Execute();
  2893. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2894. }
  2895. }
  2896. #endregion Teardown
  2897. }
  2898. [TestMethod]
  2899. public async Task Sftp_ExistsAsync()
  2900. {
  2901. const string remoteHome = "/home/sshnet";
  2902. #region Setup
  2903. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2904. {
  2905. client.Connect();
  2906. #region Clean-up
  2907. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  2908. {
  2909. await command.ExecuteAsync();
  2910. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2911. }
  2912. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  2913. {
  2914. await command.ExecuteAsync();
  2915. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2916. }
  2917. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  2918. )
  2919. {
  2920. await command.ExecuteAsync();
  2921. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2922. }
  2923. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  2924. {
  2925. await command.ExecuteAsync();
  2926. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2927. }
  2928. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  2929. {
  2930. await command.ExecuteAsync();
  2931. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2932. }
  2933. #endregion Clean-up
  2934. #region Setup
  2935. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  2936. {
  2937. await command.ExecuteAsync();
  2938. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2939. }
  2940. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  2941. {
  2942. await command.ExecuteAsync();
  2943. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2944. }
  2945. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  2946. {
  2947. await command.ExecuteAsync();
  2948. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2949. }
  2950. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  2951. {
  2952. await command.ExecuteAsync();
  2953. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2954. }
  2955. #endregion Setup
  2956. }
  2957. #endregion Setup
  2958. #region Assert
  2959. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2960. {
  2961. await client.ConnectAsync(default).ConfigureAwait(false);
  2962. Assert.IsFalse(await client.ExistsAsync(remoteHome + "/DoesNotExist"));
  2963. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/file.exists"));
  2964. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/symlink.to.file.exists"));
  2965. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/directory.exists"));
  2966. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/symlink.to.directory.exists"));
  2967. }
  2968. #endregion Assert
  2969. #region Teardown
  2970. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2971. {
  2972. client.Connect();
  2973. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  2974. {
  2975. await command.ExecuteAsync();
  2976. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2977. }
  2978. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  2979. {
  2980. await command.ExecuteAsync();
  2981. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2982. }
  2983. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  2984. {
  2985. await command.ExecuteAsync();
  2986. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2987. }
  2988. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  2989. {
  2990. await command.ExecuteAsync();
  2991. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2992. }
  2993. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  2994. {
  2995. await command.ExecuteAsync();
  2996. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2997. }
  2998. }
  2999. #endregion Teardown
  3000. }
  3001. [TestMethod]
  3002. public void Sftp_ListDirectory()
  3003. {
  3004. const string remoteDirectory = "/home/sshnet/test123";
  3005. try
  3006. {
  3007. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3008. {
  3009. client.Connect();
  3010. client.RunCommand($@"rm -Rf ""{remoteDirectory}""");
  3011. client.RunCommand($@"mkdir -p ""{remoteDirectory}""");
  3012. client.RunCommand($@"mkdir -p ""{remoteDirectory}/sub""");
  3013. client.RunCommand($@"touch ""{remoteDirectory}/file1""");
  3014. client.RunCommand($@"touch ""{remoteDirectory}/file2""");
  3015. }
  3016. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3017. {
  3018. client.Connect();
  3019. client.ChangeDirectory(remoteDirectory);
  3020. var directoryContent = client.ListDirectory(".").OrderBy(p => p.Name).ToList();
  3021. Assert.AreEqual(5, directoryContent.Count);
  3022. Assert.AreEqual(".", directoryContent[0].Name);
  3023. Assert.AreEqual($"{remoteDirectory}/.", directoryContent[0].FullName);
  3024. Assert.IsTrue(directoryContent[0].IsDirectory);
  3025. Assert.AreEqual("..", directoryContent[1].Name);
  3026. Assert.AreEqual($"{remoteDirectory}/..", directoryContent[1].FullName);
  3027. Assert.IsTrue(directoryContent[1].IsDirectory);
  3028. Assert.AreEqual("file1", directoryContent[2].Name);
  3029. Assert.AreEqual($"{remoteDirectory}/file1", directoryContent[2].FullName);
  3030. Assert.IsFalse(directoryContent[2].IsDirectory);
  3031. Assert.AreEqual("file2", directoryContent[3].Name);
  3032. Assert.AreEqual($"{remoteDirectory}/file2", directoryContent[3].FullName);
  3033. Assert.IsFalse(directoryContent[3].IsDirectory);
  3034. Assert.AreEqual("sub", directoryContent[4].Name);
  3035. Assert.AreEqual($"{remoteDirectory}/sub", directoryContent[4].FullName);
  3036. Assert.IsTrue(directoryContent[4].IsDirectory);
  3037. }
  3038. }
  3039. finally
  3040. {
  3041. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3042. {
  3043. client.Connect();
  3044. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3045. {
  3046. command.Execute();
  3047. }
  3048. }
  3049. }
  3050. }
  3051. [TestMethod]
  3052. public void Sftp_ChangeDirectory_DirectoryDoesNotExist()
  3053. {
  3054. const string remoteDirectory = "/home/sshnet/test123";
  3055. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3056. {
  3057. client.Connect();
  3058. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3059. {
  3060. command.Execute();
  3061. }
  3062. }
  3063. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3064. {
  3065. client.Connect();
  3066. try
  3067. {
  3068. client.ChangeDirectory(remoteDirectory);
  3069. Assert.Fail();
  3070. }
  3071. catch (SftpPathNotFoundException)
  3072. {
  3073. }
  3074. }
  3075. }
  3076. [TestMethod]
  3077. public async Task Sftp_ChangeDirectory_DirectoryDoesNotExistAsync()
  3078. {
  3079. const string remoteDirectory = "/home/sshnet/test123";
  3080. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3081. {
  3082. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3083. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3084. {
  3085. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3086. }
  3087. }
  3088. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3089. {
  3090. client.Connect();
  3091. try
  3092. {
  3093. await client.ChangeDirectoryAsync(remoteDirectory, CancellationToken.None).ConfigureAwait(false);
  3094. Assert.Fail();
  3095. }
  3096. catch (SftpPathNotFoundException)
  3097. {
  3098. }
  3099. }
  3100. }
  3101. [TestMethod]
  3102. public void Sftp_ChangeDirectory_DirectoryExists()
  3103. {
  3104. const string remoteDirectory = "/home/sshnet/test123";
  3105. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3106. {
  3107. client.Connect();
  3108. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3109. {
  3110. command.Execute();
  3111. }
  3112. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3113. {
  3114. command.Execute();
  3115. }
  3116. }
  3117. try
  3118. {
  3119. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3120. {
  3121. client.Connect();
  3122. client.ChangeDirectory(remoteDirectory);
  3123. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3124. using (var uploadStream = CreateMemoryStream(100))
  3125. {
  3126. uploadStream.Position = 0;
  3127. client.UploadFile(uploadStream, "gert.txt");
  3128. uploadStream.Position = 0;
  3129. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3130. {
  3131. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3132. }
  3133. }
  3134. }
  3135. }
  3136. finally
  3137. {
  3138. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3139. {
  3140. client.Connect();
  3141. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3142. {
  3143. command.Execute();
  3144. }
  3145. }
  3146. }
  3147. }
  3148. [TestMethod]
  3149. public async Task Sftp_ChangeDirectory_DirectoryExistsAsync()
  3150. {
  3151. const string remoteDirectory = "/home/sshnet/test123";
  3152. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3153. {
  3154. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3155. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3156. {
  3157. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3158. }
  3159. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3160. {
  3161. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3162. }
  3163. }
  3164. try
  3165. {
  3166. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3167. {
  3168. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3169. await client.ChangeDirectoryAsync(remoteDirectory, CancellationToken.None).ConfigureAwait(false);
  3170. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3171. using (var uploadStream = CreateMemoryStream(100))
  3172. {
  3173. uploadStream.Position = 0;
  3174. await client.UploadFileAsync(uploadStream, "gert.txt").ConfigureAwait(false);
  3175. uploadStream.Position = 0;
  3176. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3177. {
  3178. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3179. }
  3180. }
  3181. }
  3182. }
  3183. finally
  3184. {
  3185. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3186. {
  3187. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3188. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3189. {
  3190. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3191. }
  3192. }
  3193. }
  3194. }
  3195. [TestMethod]
  3196. public void Sftp_SubsystemExecution_Failed()
  3197. {
  3198. var remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
  3199. // Disable SFTP subsystem
  3200. remoteSshdConfig.ClearSubsystems()
  3201. .Update()
  3202. .Restart();
  3203. var remoteSshdReconfiguredToDefaultState = false;
  3204. try
  3205. {
  3206. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3207. {
  3208. try
  3209. {
  3210. client.Connect();
  3211. Assert.Fail("Establishing SFTP connection should have failed.");
  3212. }
  3213. catch (SshException ex)
  3214. {
  3215. Assert.IsNull(ex.InnerException);
  3216. Assert.AreEqual("Subsystem 'sftp' could not be executed.", ex.Message);
  3217. }
  3218. // Re-enable SFTP subsystem
  3219. remoteSshdConfig.Reset();
  3220. remoteSshdReconfiguredToDefaultState = true;
  3221. // ensure we can reconnect the same SftpClient instance
  3222. client.Connect();
  3223. // ensure SFTP session is correctly established
  3224. Assert.IsTrue(client.Exists("."));
  3225. }
  3226. }
  3227. finally
  3228. {
  3229. if (!remoteSshdReconfiguredToDefaultState)
  3230. {
  3231. remoteSshdConfig.Reset();
  3232. }
  3233. }
  3234. }
  3235. [TestMethod]
  3236. public void Sftp_SftpFileStream_ReadAndWrite()
  3237. {
  3238. TestReadAndWrite(
  3239. (s, buffer, offset, count) => s.Read(buffer, offset, count),
  3240. (s, buffer, offset, count) => s.Write(buffer, offset, count));
  3241. }
  3242. [TestMethod]
  3243. public void Sftp_SftpFileStream_ReadAndWriteByte()
  3244. {
  3245. TestReadAndWrite(
  3246. read: (s, buffer, offset, count) =>
  3247. {
  3248. int bytesRead = 0;
  3249. int b;
  3250. while (bytesRead < count && (b = s.ReadByte()) != -1)
  3251. {
  3252. buffer[offset + bytesRead] = (byte)b;
  3253. bytesRead++;
  3254. }
  3255. return bytesRead;
  3256. },
  3257. write: (s, buffer, offset, count) =>
  3258. {
  3259. for (int i = 0; i < count; i++)
  3260. {
  3261. s.WriteByte(buffer[offset + i]);
  3262. }
  3263. });
  3264. }
  3265. [TestMethod]
  3266. public void Sftp_SftpFileStream_ReadAndWriteAsync()
  3267. {
  3268. TestReadAndWrite(
  3269. (s, buffer, offset, count) => s.ReadAsync(buffer, offset, count).GetAwaiter().GetResult(),
  3270. (s, buffer, offset, count) => s.WriteAsync(buffer, offset, count).GetAwaiter().GetResult());
  3271. }
  3272. [TestMethod]
  3273. public void Sftp_SftpFileStream_ReadAndWriteBeginEnd()
  3274. {
  3275. TestReadAndWrite(
  3276. (s, buffer, offset, count) => s.EndRead(s.BeginRead(buffer, offset, count, null, null)),
  3277. (s, buffer, offset, count) => s.EndWrite(s.BeginWrite(buffer, offset, count, null, null)));
  3278. }
  3279. #if NET
  3280. [TestMethod]
  3281. public void Sftp_SftpFileStream_ReadAndWriteSpan()
  3282. {
  3283. TestReadAndWrite(
  3284. (s, buffer, offset, count) => s.Read(buffer.AsSpan(offset, count)),
  3285. (s, buffer, offset, count) => s.Write(buffer.AsSpan(offset, count)));
  3286. }
  3287. [TestMethod]
  3288. public void Sftp_SftpFileStream_ReadAndWriteAsyncMemory()
  3289. {
  3290. TestReadAndWrite(
  3291. (s, buffer, offset, count) => s.ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(),
  3292. (s, buffer, offset, count) => s.WriteAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult());
  3293. }
  3294. #endif
  3295. private void TestReadAndWrite(
  3296. Func<SftpFileStream, byte[], int, int, int> read,
  3297. Action<SftpFileStream, byte[], int, int> write)
  3298. {
  3299. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3300. {
  3301. client.Connect();
  3302. var remoteFile = GenerateUniqueRemoteFileName();
  3303. if (client.Exists(remoteFile))
  3304. {
  3305. client.DeleteFile(remoteFile);
  3306. }
  3307. try
  3308. {
  3309. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3310. {
  3311. Assert.IsFalse(s.CanRead);
  3312. Assert.IsTrue(s.CanWrite);
  3313. write(s, new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3314. }
  3315. // switch from read to write mode
  3316. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3317. {
  3318. Assert.IsTrue(s.CanRead);
  3319. Assert.IsTrue(s.CanWrite);
  3320. Assert.AreEqual(4, ReadByte(s));
  3321. Assert.AreEqual(3, ReadByte(s));
  3322. Assert.AreEqual(2, s.Position);
  3323. WriteByte(s, 7);
  3324. write(s, new byte[] { 8, 9, 10, 11, 12 }, 1, 3);
  3325. Assert.AreEqual(6, s.Position);
  3326. }
  3327. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3328. {
  3329. Assert.IsTrue(s.CanRead);
  3330. Assert.IsFalse(s.CanWrite);
  3331. Assert.AreEqual(6, s.Length);
  3332. var buffer = new byte[s.Length];
  3333. Assert.AreEqual(6, read(s, buffer, 0, buffer.Length));
  3334. CollectionAssert.AreEqual(new byte[] { 4, 3, 7, 9, 10, 11 }, buffer);
  3335. // Ensure we've reached end of the stream
  3336. Assert.AreEqual(-1, ReadByte(s));
  3337. }
  3338. // switch from read to write mode, and back to read mode and finally
  3339. // append a byte
  3340. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3341. {
  3342. Assert.AreEqual(4, ReadByte(s));
  3343. Assert.AreEqual(3, ReadByte(s));
  3344. Assert.AreEqual(7, ReadByte(s));
  3345. write(s, new byte[] { 0, 1, 6, 4 }, 1, 2);
  3346. Assert.AreEqual(11, ReadByte(s));
  3347. // Ensure we've reached end of the stream
  3348. Assert.AreEqual(-1, ReadByte(s));
  3349. WriteByte(s, 12);
  3350. }
  3351. // switch from write to read mode, and back to write mode
  3352. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3353. {
  3354. WriteByte(s, 5);
  3355. Assert.AreEqual(3, ReadByte(s));
  3356. WriteByte(s, 13);
  3357. Assert.AreEqual(3, s.Position);
  3358. }
  3359. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3360. {
  3361. Assert.AreEqual(7, s.Length);
  3362. var buffer = new byte[s.Length];
  3363. Assert.AreEqual(7, read(s, buffer, 0, buffer.Length));
  3364. CollectionAssert.AreEqual(new byte[] { 5, 3, 13, 1, 6, 11, 12 }, buffer);
  3365. // Ensure we've reached end of the stream
  3366. Assert.AreEqual(-1, ReadByte(s));
  3367. }
  3368. }
  3369. finally
  3370. {
  3371. if (client.Exists(remoteFile))
  3372. {
  3373. client.DeleteFile(remoteFile);
  3374. }
  3375. }
  3376. }
  3377. int ReadByte(SftpFileStream s)
  3378. {
  3379. var buffer = new byte[1];
  3380. var bytesRead = read(s, buffer, 0, 1);
  3381. return bytesRead == 0 ? -1 : buffer[0];
  3382. }
  3383. void WriteByte(SftpFileStream s, byte b)
  3384. {
  3385. write(s, [b], 0, 1);
  3386. }
  3387. }
  3388. [TestMethod]
  3389. public void Sftp_SftpFileStream_SetLength_ReduceLength()
  3390. {
  3391. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3392. {
  3393. client.Connect();
  3394. var remoteFile = GenerateUniqueRemoteFileName();
  3395. if (client.Exists(remoteFile))
  3396. {
  3397. client.DeleteFile(remoteFile);
  3398. }
  3399. try
  3400. {
  3401. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3402. {
  3403. s.Write(new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3404. }
  3405. // reduce length while in write mode, with data in write buffer, and before
  3406. // current position
  3407. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  3408. {
  3409. s.Position = 3;
  3410. s.Write(new byte[] { 6, 7, 8, 9 }, offset: 0, count: 4);
  3411. Assert.AreEqual(7, s.Position);
  3412. // verify buffer has not yet been flushed
  3413. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3414. {
  3415. Assert.AreEqual(4, fs.ReadByte());
  3416. Assert.AreEqual(3, fs.ReadByte());
  3417. Assert.AreEqual(2, fs.ReadByte());
  3418. // Ensure we've reached end of the stream
  3419. Assert.AreEqual(-1, fs.ReadByte());
  3420. }
  3421. s.SetLength(5);
  3422. Assert.AreEqual(5, s.Position);
  3423. // verify that buffer was flushed and size has been modified
  3424. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3425. {
  3426. Assert.AreEqual(4, fs.ReadByte());
  3427. Assert.AreEqual(3, fs.ReadByte());
  3428. Assert.AreEqual(2, fs.ReadByte());
  3429. Assert.AreEqual(6, fs.ReadByte());
  3430. Assert.AreEqual(7, fs.ReadByte());
  3431. // Ensure we've reached end of the stream
  3432. Assert.AreEqual(-1, fs.ReadByte());
  3433. }
  3434. s.WriteByte(1);
  3435. }
  3436. // verify that last byte was correctly written to the file
  3437. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3438. {
  3439. Assert.AreEqual(6, s.Length);
  3440. var buffer = new byte[s.Length + 2];
  3441. Assert.AreEqual(6, s.Read(buffer, offset: 0, buffer.Length));
  3442. CollectionAssert.AreEqual(new byte[] { 4, 3, 2, 6, 7, 1, 0, 0 }, buffer);
  3443. // Ensure we've reached end of the stream
  3444. Assert.AreEqual(-1, s.ReadByte());
  3445. }
  3446. // reduce length while in read mode, but beyond current position
  3447. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3448. {
  3449. var buffer = new byte[1];
  3450. Assert.AreEqual(1, s.Read(buffer, offset: 0, buffer.Length));
  3451. CollectionAssert.AreEqual(new byte[] { 4 }, buffer);
  3452. s.SetLength(3);
  3453. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  3454. {
  3455. w.Write(new byte[] { 8, 1, 6, 2 }, offset: 0, count: 4);
  3456. }
  3457. // verify that position was not changed
  3458. Assert.AreEqual(1, s.Position);
  3459. // verify that read buffer was cleared
  3460. Assert.AreEqual(1, s.ReadByte());
  3461. Assert.AreEqual(6, s.ReadByte());
  3462. Assert.AreEqual(2, s.ReadByte());
  3463. // Ensure we've reached end of the stream
  3464. Assert.AreEqual(-1, s.ReadByte());
  3465. Assert.AreEqual(4, s.Length);
  3466. }
  3467. // reduce length while in read mode, but before current position
  3468. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3469. {
  3470. var buffer = new byte[4];
  3471. Assert.AreEqual(4, s.Read(buffer, offset: 0, buffer.Length));
  3472. CollectionAssert.AreEqual(new byte[] { 8, 1, 6, 2 }, buffer);
  3473. Assert.AreEqual(4, s.Position);
  3474. s.SetLength(3);
  3475. // verify that position was moved to last byte
  3476. Assert.AreEqual(3, s.Position);
  3477. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3478. {
  3479. Assert.AreEqual(3, w.Length);
  3480. Assert.AreEqual(8, w.ReadByte());
  3481. Assert.AreEqual(1, w.ReadByte());
  3482. Assert.AreEqual(6, w.ReadByte());
  3483. // Ensure we've reached end of the stream
  3484. Assert.AreEqual(-1, w.ReadByte());
  3485. }
  3486. // Ensure we've reached end of the stream
  3487. Assert.AreEqual(-1, s.ReadByte());
  3488. }
  3489. }
  3490. finally
  3491. {
  3492. if (client.Exists(remoteFile))
  3493. {
  3494. client.DeleteFile(remoteFile);
  3495. }
  3496. }
  3497. }
  3498. }
  3499. [TestMethod]
  3500. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginBegin()
  3501. {
  3502. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3503. {
  3504. client.BufferSize = 500;
  3505. client.Connect();
  3506. var remoteFile = GenerateUniqueRemoteFileName();
  3507. if (client.Exists(remoteFile))
  3508. {
  3509. client.DeleteFile(remoteFile);
  3510. }
  3511. try
  3512. {
  3513. // create single-byte file
  3514. using (var fs = client.OpenWrite(remoteFile))
  3515. {
  3516. fs.WriteByte(0x04);
  3517. }
  3518. // seek beyond EOF but not beyond buffer size
  3519. // do not write anything
  3520. using (var fs = client.OpenWrite(remoteFile))
  3521. {
  3522. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3523. Assert.AreEqual(3, newPosition);
  3524. Assert.AreEqual(3, fs.Position);
  3525. Assert.AreEqual(1, fs.Length);
  3526. }
  3527. using (var fs = client.OpenRead(remoteFile))
  3528. {
  3529. Assert.AreEqual(1, fs.Length);
  3530. Assert.AreEqual(0x04, fs.ReadByte());
  3531. // Ensure we've reached end of the stream
  3532. Assert.AreEqual(-1, fs.ReadByte());
  3533. }
  3534. client.DeleteFile(remoteFile);
  3535. // create single-byte file
  3536. using (var fs = client.OpenWrite(remoteFile))
  3537. {
  3538. fs.WriteByte(0x04);
  3539. }
  3540. // seek beyond EOF and beyond buffer size
  3541. // do not write anything
  3542. using (var fs = client.OpenWrite(remoteFile))
  3543. {
  3544. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  3545. Assert.AreEqual(700, newPosition);
  3546. Assert.AreEqual(700, fs.Position);
  3547. Assert.AreEqual(1, fs.Length);
  3548. }
  3549. using (var fs = client.OpenRead(remoteFile))
  3550. {
  3551. Assert.AreEqual(1, fs.Length);
  3552. Assert.AreEqual(0x04, fs.ReadByte());
  3553. // Ensure we've reached end of the stream
  3554. Assert.AreEqual(-1, fs.ReadByte());
  3555. }
  3556. client.DeleteFile(remoteFile);
  3557. // create single-byte file
  3558. using (var fs = client.OpenWrite(remoteFile))
  3559. {
  3560. fs.WriteByte(0x04);
  3561. }
  3562. // seek beyond EOF but not beyond buffer size
  3563. // write less bytes than buffer size
  3564. var seekOffset = 3L;
  3565. // buffer holding the data that we'll write to the file
  3566. var writeBuffer = GenerateRandom(size: 7);
  3567. using (var fs = client.OpenWrite(remoteFile))
  3568. {
  3569. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3570. Assert.AreEqual(seekOffset, newPosition);
  3571. Assert.AreEqual(seekOffset, fs.Position);
  3572. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3573. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3574. }
  3575. using (var fs = client.OpenRead(remoteFile))
  3576. {
  3577. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3578. Assert.AreEqual(0x04, fs.ReadByte());
  3579. var soughtOverReadBuffer = new byte[seekOffset - 1];
  3580. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3581. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  3582. var readBuffer = new byte[writeBuffer.Length];
  3583. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3584. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3585. // Ensure we've reached end of the stream
  3586. Assert.AreEqual(-1, fs.ReadByte());
  3587. }
  3588. client.DeleteFile(remoteFile);
  3589. // create single-byte file
  3590. using (var fs = client.OpenWrite(remoteFile))
  3591. {
  3592. fs.WriteByte(0x04);
  3593. }
  3594. // seek beyond EOF and beyond buffer size
  3595. // write less bytes than buffer size
  3596. seekOffset = 700L;
  3597. // buffer holding the data that we'll write to the file
  3598. writeBuffer = GenerateRandom(size: 4);
  3599. using (var fs = client.OpenWrite(remoteFile))
  3600. {
  3601. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3602. Assert.AreEqual(seekOffset, newPosition);
  3603. Assert.AreEqual(seekOffset, fs.Position);
  3604. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3605. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3606. }
  3607. using (var fs = client.OpenRead(remoteFile))
  3608. {
  3609. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3610. Assert.AreEqual(0x04, fs.ReadByte());
  3611. var soughtOverReadBuffer = new byte[seekOffset - 1];
  3612. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3613. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  3614. var readBuffer = new byte[writeBuffer.Length];
  3615. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3616. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3617. // Ensure we've reached end of the stream
  3618. Assert.AreEqual(-1, fs.ReadByte());
  3619. }
  3620. client.DeleteFile(remoteFile);
  3621. // create single-byte file
  3622. using (var fs = client.OpenWrite(remoteFile))
  3623. {
  3624. fs.WriteByte(0x04);
  3625. }
  3626. // seek beyond EOF but not beyond buffer size
  3627. // write more bytes than buffer size
  3628. writeBuffer = GenerateRandom(size: 600);
  3629. using (var fs = client.OpenWrite(remoteFile))
  3630. {
  3631. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3632. Assert.AreEqual(3, newPosition);
  3633. Assert.AreEqual(3, fs.Position);
  3634. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3635. }
  3636. using (var fs = client.OpenRead(remoteFile))
  3637. {
  3638. Assert.AreEqual(3 + writeBuffer.Length, fs.Length);
  3639. Assert.AreEqual(0x04, fs.ReadByte());
  3640. Assert.AreEqual(0x00, fs.ReadByte());
  3641. Assert.AreEqual(0x00, fs.ReadByte());
  3642. var readBuffer = new byte[writeBuffer.Length];
  3643. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3644. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3645. // Ensure we've reached end of the stream
  3646. Assert.AreEqual(-1, fs.ReadByte());
  3647. }
  3648. client.DeleteFile(remoteFile);
  3649. // create single-byte file
  3650. using (var fs = client.OpenWrite(remoteFile))
  3651. {
  3652. fs.WriteByte(0x04);
  3653. }
  3654. // seek beyond EOF and beyond buffer size
  3655. // write more bytes than buffer size
  3656. writeBuffer = GenerateRandom(size: 600);
  3657. using (var fs = client.OpenWrite(remoteFile))
  3658. {
  3659. var newPosition = fs.Seek(offset: 550, SeekOrigin.Begin);
  3660. Assert.AreEqual(550, newPosition);
  3661. Assert.AreEqual(550, fs.Position);
  3662. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3663. }
  3664. using (var fs = client.OpenRead(remoteFile))
  3665. {
  3666. Assert.AreEqual(550 + writeBuffer.Length, fs.Length);
  3667. Assert.AreEqual(0x04, fs.ReadByte());
  3668. var soughtOverReadBuffer = new byte[550 - 1];
  3669. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3670. CollectionAssert.AreEqual(new byte[550 - 1], soughtOverReadBuffer);
  3671. var readBuffer = new byte[writeBuffer.Length];
  3672. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3673. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3674. // Ensure we've reached end of the stream
  3675. Assert.AreEqual(-1, fs.ReadByte());
  3676. }
  3677. }
  3678. finally
  3679. {
  3680. if (client.Exists(remoteFile))
  3681. {
  3682. client.DeleteFile(remoteFile);
  3683. }
  3684. }
  3685. }
  3686. }
  3687. [TestMethod]
  3688. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginEnd()
  3689. {
  3690. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3691. {
  3692. client.BufferSize = 500;
  3693. client.Connect();
  3694. var remoteFile = GenerateUniqueRemoteFileName();
  3695. if (client.Exists(remoteFile))
  3696. {
  3697. client.DeleteFile(remoteFile);
  3698. }
  3699. try
  3700. {
  3701. // create single-byte file
  3702. using (var fs = client.OpenWrite(remoteFile))
  3703. {
  3704. fs.WriteByte(0x04);
  3705. }
  3706. // seek beyond EOF but not beyond buffer size
  3707. // do not write anything
  3708. using (var fs = client.OpenWrite(remoteFile))
  3709. {
  3710. var newPosition = fs.Seek(offset: 3L, SeekOrigin.End);
  3711. Assert.AreEqual(4, newPosition);
  3712. Assert.AreEqual(4, fs.Position);
  3713. Assert.AreEqual(1, fs.Length);
  3714. }
  3715. using (var fs = client.OpenRead(remoteFile))
  3716. {
  3717. Assert.AreEqual(1, fs.Length);
  3718. Assert.AreEqual(0x04, fs.ReadByte());
  3719. // Ensure we've reached end of the stream
  3720. Assert.AreEqual(-1, fs.ReadByte());
  3721. }
  3722. client.DeleteFile(remoteFile);
  3723. // create single-byte file
  3724. using (var fs = client.OpenWrite(remoteFile))
  3725. {
  3726. fs.WriteByte(0x04);
  3727. }
  3728. // seek beyond EOF and beyond buffer size
  3729. // do not write anything
  3730. using (var fs = client.OpenWrite(remoteFile))
  3731. {
  3732. var newPosition = fs.Seek(offset: 700L, SeekOrigin.End);
  3733. Assert.AreEqual(701, newPosition);
  3734. Assert.AreEqual(701, fs.Position);
  3735. Assert.AreEqual(1, fs.Length);
  3736. }
  3737. using (var fs = client.OpenRead(remoteFile))
  3738. {
  3739. Assert.AreEqual(1, fs.Length);
  3740. Assert.AreEqual(0x04, fs.ReadByte());
  3741. // Ensure we've reached end of the stream
  3742. Assert.AreEqual(-1, fs.ReadByte());
  3743. }
  3744. client.DeleteFile(remoteFile);
  3745. // create single-byte file
  3746. using (var fs = client.OpenWrite(remoteFile))
  3747. {
  3748. fs.WriteByte(0x04);
  3749. }
  3750. // seek beyond EOF but not beyond buffer size
  3751. // write less bytes than buffer size
  3752. var seekOffset = 3L;
  3753. // buffer holding the data that we'll write to the file
  3754. var writeBuffer = GenerateRandom(size: 7);
  3755. using (var fs = client.OpenWrite(remoteFile))
  3756. {
  3757. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3758. Assert.AreEqual(4, newPosition);
  3759. Assert.AreEqual(4, fs.Position);
  3760. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3761. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3762. }
  3763. using (var fs = client.OpenRead(remoteFile))
  3764. {
  3765. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3766. Assert.AreEqual(0x04, fs.ReadByte());
  3767. var soughtOverReadBuffer = new byte[seekOffset];
  3768. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3769. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  3770. var readBuffer = new byte[writeBuffer.Length];
  3771. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3772. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3773. // Ensure we've reached end of the stream
  3774. Assert.AreEqual(-1, fs.ReadByte());
  3775. }
  3776. client.DeleteFile(remoteFile);
  3777. // create single-byte file
  3778. using (var fs = client.OpenWrite(remoteFile))
  3779. {
  3780. fs.WriteByte(0x04);
  3781. }
  3782. // seek beyond EOF and beyond buffer size
  3783. // write less bytes than buffer size
  3784. seekOffset = 700L;
  3785. // buffer holding the data that we'll write to the file
  3786. writeBuffer = GenerateRandom(size: 4);
  3787. using (var fs = client.OpenWrite(remoteFile))
  3788. {
  3789. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3790. Assert.AreEqual(1 + seekOffset, newPosition);
  3791. Assert.AreEqual(1 + seekOffset, fs.Position);
  3792. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3793. }
  3794. using (var fs = client.OpenRead(remoteFile))
  3795. {
  3796. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3797. Assert.AreEqual(0x04, fs.ReadByte());
  3798. var soughtOverReadBuffer = new byte[seekOffset];
  3799. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3800. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  3801. var readBuffer = new byte[writeBuffer.Length];
  3802. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3803. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3804. // Ensure we've reached end of the stream
  3805. Assert.AreEqual(-1, fs.ReadByte());
  3806. }
  3807. client.DeleteFile(remoteFile);
  3808. // create single-byte file
  3809. using (var fs = client.OpenWrite(remoteFile))
  3810. {
  3811. fs.WriteByte(0x04);
  3812. }
  3813. // seek beyond EOF but not beyond buffer size
  3814. // write more bytes than buffer size
  3815. seekOffset = 3L;
  3816. writeBuffer = GenerateRandom(size: 600);
  3817. using (var fs = client.OpenWrite(remoteFile))
  3818. {
  3819. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3820. Assert.AreEqual(1 + seekOffset, newPosition);
  3821. Assert.AreEqual(1 + seekOffset, fs.Position);
  3822. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3823. }
  3824. using (var fs = client.OpenRead(remoteFile))
  3825. {
  3826. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3827. Assert.AreEqual(0x04, fs.ReadByte());
  3828. var soughtOverReadBuffer = new byte[seekOffset];
  3829. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3830. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  3831. var readBuffer = new byte[writeBuffer.Length];
  3832. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3833. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3834. // Ensure we've reached end of the stream
  3835. Assert.AreEqual(-1, fs.ReadByte());
  3836. }
  3837. client.DeleteFile(remoteFile);
  3838. // create single-byte file
  3839. using (var fs = client.OpenWrite(remoteFile))
  3840. {
  3841. fs.WriteByte(0x04);
  3842. }
  3843. // seek beyond EOF and beyond buffer size
  3844. // write more bytes than buffer size
  3845. seekOffset = 550L;
  3846. writeBuffer = GenerateRandom(size: 600);
  3847. using (var fs = client.OpenWrite(remoteFile))
  3848. {
  3849. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3850. Assert.AreEqual(1 + seekOffset, newPosition);
  3851. Assert.AreEqual(1 + seekOffset, fs.Position);
  3852. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3853. }
  3854. using (var fs = client.OpenRead(remoteFile))
  3855. {
  3856. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3857. Assert.AreEqual(0x04, fs.ReadByte());
  3858. var soughtOverReadBuffer = new byte[seekOffset];
  3859. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3860. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  3861. var readBuffer = new byte[writeBuffer.Length];
  3862. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3863. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3864. // Ensure we've reached end of the stream
  3865. Assert.AreEqual(-1, fs.ReadByte());
  3866. }
  3867. }
  3868. finally
  3869. {
  3870. if (client.Exists(remoteFile))
  3871. {
  3872. client.DeleteFile(remoteFile);
  3873. }
  3874. }
  3875. }
  3876. }
  3877. [TestMethod]
  3878. public void Sftp_SftpFileStream_Seek_NegativeOffSet_SeekOriginEnd()
  3879. {
  3880. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3881. {
  3882. client.BufferSize = 500;
  3883. client.Connect();
  3884. var remoteFile = GenerateUniqueRemoteFileName();
  3885. if (client.Exists(remoteFile))
  3886. {
  3887. client.DeleteFile(remoteFile);
  3888. }
  3889. try
  3890. {
  3891. using (var fs = client.OpenWrite(remoteFile))
  3892. {
  3893. fs.WriteByte(0x04);
  3894. fs.WriteByte(0x07);
  3895. fs.WriteByte(0x05);
  3896. }
  3897. // seek within file and not beyond buffer size
  3898. // do not write anything
  3899. using (var fs = client.OpenWrite(remoteFile))
  3900. {
  3901. var newPosition = fs.Seek(offset: -2L, SeekOrigin.End);
  3902. Assert.AreEqual(1, newPosition);
  3903. Assert.AreEqual(1, fs.Position);
  3904. }
  3905. using (var fs = client.OpenRead(remoteFile))
  3906. {
  3907. Assert.AreEqual(3, fs.Length);
  3908. Assert.AreEqual(0x04, fs.ReadByte());
  3909. Assert.AreEqual(0x07, fs.ReadByte());
  3910. Assert.AreEqual(0x05, fs.ReadByte());
  3911. // Ensure we've reached end of the stream
  3912. Assert.AreEqual(-1, fs.ReadByte());
  3913. }
  3914. client.DeleteFile(remoteFile);
  3915. // buffer holding the data that we'll write to the file
  3916. var writeBuffer = GenerateRandom(size: (int)client.BufferSize + 200);
  3917. using (var fs = client.OpenWrite(remoteFile))
  3918. {
  3919. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3920. }
  3921. // seek within EOF and beyond buffer size
  3922. // do not write anything
  3923. using (var fs = client.OpenWrite(remoteFile))
  3924. {
  3925. var newPosition = fs.Seek(offset: -100L, SeekOrigin.End);
  3926. Assert.AreEqual(600, newPosition);
  3927. Assert.AreEqual(600, fs.Position);
  3928. }
  3929. using (var fs = client.OpenRead(remoteFile))
  3930. {
  3931. Assert.AreEqual(writeBuffer.Length, fs.Length);
  3932. var readBuffer = new byte[writeBuffer.Length];
  3933. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3934. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3935. // Ensure we've reached end of the stream
  3936. Assert.AreEqual(-1, fs.ReadByte());
  3937. }
  3938. client.DeleteFile(remoteFile);
  3939. // seek within EOF and within buffer size
  3940. // write less bytes than buffer size
  3941. using (var fs = client.OpenWrite(remoteFile))
  3942. {
  3943. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3944. var newPosition = fs.Seek(offset: -3, SeekOrigin.End);
  3945. Assert.AreEqual(697, newPosition);
  3946. Assert.AreEqual(697, fs.Position);
  3947. fs.WriteByte(0x01);
  3948. fs.WriteByte(0x05);
  3949. fs.WriteByte(0x04);
  3950. fs.WriteByte(0x07);
  3951. }
  3952. using (var fs = client.OpenRead(remoteFile))
  3953. {
  3954. Assert.AreEqual(writeBuffer.Length + 1, fs.Length);
  3955. var readBuffer = new byte[writeBuffer.Length - 3];
  3956. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3957. CollectionAssert.AreEqual(writeBuffer.Take(readBuffer.Length), readBuffer);
  3958. Assert.AreEqual(0x01, fs.ReadByte());
  3959. Assert.AreEqual(0x05, fs.ReadByte());
  3960. Assert.AreEqual(0x04, fs.ReadByte());
  3961. Assert.AreEqual(0x07, fs.ReadByte());
  3962. // Ensure we've reached end of the stream
  3963. Assert.AreEqual(-1, fs.ReadByte());
  3964. }
  3965. client.DeleteFile(remoteFile);
  3966. // buffer holding the data that we'll write to the file
  3967. writeBuffer = GenerateRandom(size: (int)client.BufferSize * 4);
  3968. // seek within EOF and beyond buffer size
  3969. // write less bytes than buffer size
  3970. using (var fs = client.OpenWrite(remoteFile))
  3971. {
  3972. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3973. var newPosition = fs.Seek(offset: -(client.BufferSize * 2), SeekOrigin.End);
  3974. Assert.AreEqual(1000, newPosition);
  3975. Assert.AreEqual(1000, fs.Position);
  3976. fs.WriteByte(0x01);
  3977. fs.WriteByte(0x05);
  3978. fs.WriteByte(0x04);
  3979. fs.WriteByte(0x07);
  3980. }
  3981. using (var fs = client.OpenRead(remoteFile))
  3982. {
  3983. Assert.AreEqual(writeBuffer.Length, fs.Length);
  3984. // First part of file should not have been touched
  3985. var readBuffer = new byte[(int)client.BufferSize * 2];
  3986. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3987. CollectionAssert.AreEqual(writeBuffer.Take(readBuffer.Length), readBuffer);
  3988. // Check part that should have been updated
  3989. Assert.AreEqual(0x01, fs.ReadByte());
  3990. Assert.AreEqual(0x05, fs.ReadByte());
  3991. Assert.AreEqual(0x04, fs.ReadByte());
  3992. Assert.AreEqual(0x07, fs.ReadByte());
  3993. // Remaining bytes should not have been touched
  3994. readBuffer = new byte[((int)client.BufferSize * 2) - 4];
  3995. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3996. CollectionAssert.AreEqual(
  3997. writeBuffer.Skip(((int)client.BufferSize * 2) + 4).Take(readBuffer.Length).ToArray(),
  3998. readBuffer);
  3999. // Ensure we've reached end of the stream
  4000. Assert.AreEqual(-1, fs.ReadByte());
  4001. }
  4002. }
  4003. finally
  4004. {
  4005. if (client.Exists(remoteFile))
  4006. {
  4007. client.DeleteFile(remoteFile);
  4008. }
  4009. }
  4010. }
  4011. }
  4012. /// https://github.com/sshnet/SSH.NET/issues/253
  4013. [TestMethod]
  4014. public void Sftp_SftpFileStream_Seek_Issue253()
  4015. {
  4016. var buf = Encoding.UTF8.GetBytes("123456");
  4017. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4018. {
  4019. client.Connect();
  4020. var remoteFile = GenerateUniqueRemoteFileName();
  4021. if (client.Exists(remoteFile))
  4022. {
  4023. client.DeleteFile(remoteFile);
  4024. }
  4025. try
  4026. {
  4027. using (var ws = client.OpenWrite(remoteFile))
  4028. {
  4029. ws.Write(buf, offset: 0, count: 3);
  4030. }
  4031. using (var ws = client.OpenWrite(remoteFile))
  4032. {
  4033. var newPosition = ws.Seek(offset: 3, SeekOrigin.Begin);
  4034. Assert.AreEqual(3, newPosition);
  4035. Assert.AreEqual(3, ws.Position);
  4036. ws.Write(buf, 3, 3);
  4037. }
  4038. var actual = client.ReadAllText(remoteFile, Encoding.UTF8);
  4039. Assert.AreEqual("123456", actual);
  4040. }
  4041. finally
  4042. {
  4043. if (client.Exists(remoteFile))
  4044. {
  4045. client.DeleteFile(remoteFile);
  4046. }
  4047. }
  4048. }
  4049. }
  4050. [TestMethod]
  4051. public void Sftp_SftpFileStream_Seek_WithinReadBuffer()
  4052. {
  4053. var originalContent = GenerateRandom(size: 800);
  4054. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4055. {
  4056. client.BufferSize = 500;
  4057. client.Connect();
  4058. var remoteFile = GenerateUniqueRemoteFileName();
  4059. if (client.Exists(remoteFile))
  4060. {
  4061. client.DeleteFile(remoteFile);
  4062. }
  4063. try
  4064. {
  4065. using (var fs = client.OpenWrite(remoteFile))
  4066. {
  4067. fs.Write(originalContent, offset: 0, originalContent.Length);
  4068. }
  4069. using (var fs = client.OpenRead(remoteFile))
  4070. {
  4071. var readBuffer = new byte[200];
  4072. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  4073. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  4074. Assert.AreEqual(3L, newPosition);
  4075. Assert.AreEqual(3L, fs.Position);
  4076. }
  4077. client.DeleteFile(remoteFile);
  4078. #region Seek beyond EOF and beyond buffer size do not write anything
  4079. // create single-byte file
  4080. using (var fs = client.OpenWrite(remoteFile))
  4081. {
  4082. fs.WriteByte(0x04);
  4083. }
  4084. using (var fs = client.OpenRead(remoteFile))
  4085. {
  4086. Assert.AreEqual(1, fs.Length);
  4087. Assert.AreEqual(0x04, fs.ReadByte());
  4088. // Ensure we've reached end of the stream
  4089. Assert.AreEqual(-1, fs.ReadByte());
  4090. }
  4091. using (var fs = client.OpenWrite(remoteFile))
  4092. {
  4093. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  4094. Assert.AreEqual(700L, newPosition);
  4095. Assert.AreEqual(700L, fs.Position);
  4096. }
  4097. using (var fs = client.OpenRead(remoteFile))
  4098. {
  4099. Assert.AreEqual(1, fs.Length);
  4100. Assert.AreEqual(0x04, fs.ReadByte());
  4101. // Ensure we've reached end of the stream
  4102. Assert.AreEqual(-1, fs.ReadByte());
  4103. }
  4104. client.DeleteFile(remoteFile);
  4105. #endregion Seek beyond EOF and beyond buffer size do not write anything
  4106. #region Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4107. // create single-byte file
  4108. using (var fs = client.OpenWrite(remoteFile))
  4109. {
  4110. fs.WriteByte(0x04);
  4111. }
  4112. var seekOffset = 3L;
  4113. var writeBuffer = GenerateRandom(size: 7);
  4114. using (var fs = client.OpenWrite(remoteFile))
  4115. {
  4116. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4117. Assert.AreEqual(seekOffset, newPosition);
  4118. Assert.AreEqual(seekOffset, fs.Position);
  4119. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4120. }
  4121. using (var fs = client.OpenRead(remoteFile))
  4122. {
  4123. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4124. Assert.AreEqual(0x04, fs.ReadByte());
  4125. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4126. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  4127. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  4128. var readBuffer = new byte[writeBuffer.Length];
  4129. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  4130. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  4131. // Ensure we've reached end of the stream
  4132. Assert.AreEqual(-1, fs.ReadByte());
  4133. }
  4134. client.DeleteFile(remoteFile);
  4135. #endregion Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4136. #region Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4137. // create single-byte file
  4138. using (var fs = client.OpenWrite(remoteFile))
  4139. {
  4140. fs.WriteByte(0x04);
  4141. }
  4142. seekOffset = 700L;
  4143. writeBuffer = GenerateRandom(size: 4);
  4144. using (var fs = client.OpenWrite(remoteFile))
  4145. {
  4146. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4147. Assert.AreEqual(seekOffset, newPosition);
  4148. Assert.AreEqual(seekOffset, fs.Position);
  4149. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4150. }
  4151. using (var fs = client.OpenRead(remoteFile))
  4152. {
  4153. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4154. Assert.AreEqual(0x04, fs.ReadByte());
  4155. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4156. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  4157. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  4158. var readBuffer = new byte[writeBuffer.Length];
  4159. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  4160. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  4161. // Ensure we've reached end of the stream
  4162. Assert.AreEqual(-1, fs.ReadByte());
  4163. }
  4164. client.DeleteFile(remoteFile);
  4165. #endregion Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4166. #region Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4167. // create single-byte file
  4168. using (var fs = client.OpenWrite(remoteFile))
  4169. {
  4170. fs.WriteByte(0x04);
  4171. }
  4172. seekOffset = 3L;
  4173. writeBuffer = GenerateRandom(size: 600);
  4174. using (var fs = client.OpenWrite(remoteFile))
  4175. {
  4176. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4177. Assert.AreEqual(seekOffset, newPosition);
  4178. Assert.AreEqual(seekOffset, fs.Position);
  4179. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4180. }
  4181. using (var fs = client.OpenRead(remoteFile))
  4182. {
  4183. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4184. Assert.AreEqual(0x04, fs.ReadByte());
  4185. Assert.AreEqual(0x00, fs.ReadByte());
  4186. Assert.AreEqual(0x00, fs.ReadByte());
  4187. var readBuffer = new byte[writeBuffer.Length];
  4188. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  4189. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  4190. // Ensure we've reached end of the stream
  4191. Assert.AreEqual(-1, fs.ReadByte());
  4192. }
  4193. client.DeleteFile(remoteFile);
  4194. #endregion Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4195. #region Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4196. // create single-byte file
  4197. using (var fs = client.OpenWrite(remoteFile))
  4198. {
  4199. fs.WriteByte(0x04);
  4200. }
  4201. seekOffset = 550L;
  4202. writeBuffer = GenerateRandom(size: 600);
  4203. using (var fs = client.OpenWrite(remoteFile))
  4204. {
  4205. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4206. Assert.AreEqual(seekOffset, newPosition);
  4207. Assert.AreEqual(seekOffset, fs.Position);
  4208. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4209. }
  4210. using (var fs = client.OpenRead(remoteFile))
  4211. {
  4212. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4213. Assert.AreEqual(0x04, fs.ReadByte());
  4214. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4215. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  4216. CollectionAssert.AreEqual(new byte[seekOffset - 1], soughtOverReadBuffer);
  4217. var readBuffer = new byte[writeBuffer.Length];
  4218. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  4219. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  4220. // Ensure we've reached end of the stream
  4221. Assert.AreEqual(-1, fs.ReadByte());
  4222. }
  4223. client.DeleteFile(remoteFile);
  4224. #endregion Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4225. }
  4226. finally
  4227. {
  4228. if (client.Exists(remoteFile))
  4229. {
  4230. client.DeleteFile(remoteFile);
  4231. }
  4232. }
  4233. }
  4234. }
  4235. [TestMethod]
  4236. public void Sftp_SftpFileStream_SetLength_FileDoesNotExist()
  4237. {
  4238. var size = new Random().Next(500, 5000);
  4239. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4240. {
  4241. client.Connect();
  4242. var remoteFile = GenerateUniqueRemoteFileName();
  4243. if (client.Exists(remoteFile))
  4244. {
  4245. client.DeleteFile(remoteFile);
  4246. }
  4247. try
  4248. {
  4249. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4250. {
  4251. s.SetLength(size);
  4252. }
  4253. Assert.IsTrue(client.Exists(remoteFile));
  4254. var attributes = client.GetAttributes(remoteFile);
  4255. Assert.IsTrue(attributes.IsRegularFile);
  4256. Assert.AreEqual(size, attributes.Size);
  4257. using (var downloaded = new MemoryStream())
  4258. {
  4259. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4260. downloaded.Position = 0;
  4261. Assert.AreEqual(CreateHash(new byte[size]), CreateHash(downloaded));
  4262. }
  4263. }
  4264. finally
  4265. {
  4266. if (client.Exists(remoteFile))
  4267. {
  4268. client.DeleteFile(remoteFile);
  4269. }
  4270. }
  4271. }
  4272. }
  4273. [TestMethod]
  4274. public void Sftp_Open_Append_Write_ExistingFile()
  4275. {
  4276. const int fileSize = 5 * 1024;
  4277. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4278. using (var input = CreateMemoryStream(fileSize))
  4279. {
  4280. input.Position = 0;
  4281. client.Connect();
  4282. var remoteFile = GenerateUniqueRemoteFileName();
  4283. if (client.Exists(remoteFile))
  4284. {
  4285. client.DeleteFile(remoteFile);
  4286. }
  4287. try
  4288. {
  4289. client.UploadFile(input, remoteFile);
  4290. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4291. {
  4292. Assert.IsFalse(s.CanRead);
  4293. Assert.IsTrue(s.CanWrite);
  4294. var buffer = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4295. s.Write(buffer, offset: 0, buffer.Length);
  4296. input.Write(buffer, offset: 0, buffer.Length);
  4297. }
  4298. using (var downloaded = new MemoryStream())
  4299. {
  4300. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4301. input.Position = 0;
  4302. downloaded.Position = 0;
  4303. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4304. }
  4305. }
  4306. finally
  4307. {
  4308. if (client.Exists(remoteFile))
  4309. {
  4310. client.DeleteFile(remoteFile);
  4311. }
  4312. }
  4313. }
  4314. }
  4315. [TestMethod]
  4316. public void Sftp_Open_Append_Write_FileDoesNotExist()
  4317. {
  4318. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4319. {
  4320. client.Connect();
  4321. var remoteFile = GenerateUniqueRemoteFileName();
  4322. if (client.Exists(remoteFile))
  4323. {
  4324. client.DeleteFile(remoteFile);
  4325. }
  4326. try
  4327. {
  4328. #region Verify if merely opening the file for append creates a zero-byte file
  4329. using (client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4330. {
  4331. }
  4332. Assert.IsTrue(client.Exists(remoteFile));
  4333. var attributes = client.GetAttributes(remoteFile);
  4334. Assert.IsTrue(attributes.IsRegularFile);
  4335. Assert.AreEqual(0L, attributes.Size);
  4336. #endregion Verify if merely opening the file for append creates it
  4337. client.DeleteFile(remoteFile);
  4338. #region Verify if content is actually written to the file
  4339. var content = GenerateRandom(size: 100);
  4340. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4341. {
  4342. s.Write(content, offset: 0, content.Length);
  4343. }
  4344. using (var downloaded = new MemoryStream())
  4345. {
  4346. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4347. downloaded.Position = 0;
  4348. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4349. }
  4350. #endregion Verify if content is actually written to the file
  4351. }
  4352. finally
  4353. {
  4354. if (client.Exists(remoteFile))
  4355. {
  4356. client.DeleteFile(remoteFile);
  4357. }
  4358. }
  4359. }
  4360. }
  4361. [TestMethod]
  4362. public void Sftp_Open_PathAndMode_ModeIsCreate_FileDoesNotExist()
  4363. {
  4364. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4365. {
  4366. client.Connect();
  4367. var remoteFile = GenerateUniqueRemoteFileName();
  4368. if (client.Exists(remoteFile))
  4369. {
  4370. client.DeleteFile(remoteFile);
  4371. }
  4372. try
  4373. {
  4374. #region Verify if merely opening the file for create creates a zero-byte file
  4375. using (client.Open(remoteFile, FileMode.Create))
  4376. {
  4377. }
  4378. Assert.IsTrue(client.Exists(remoteFile));
  4379. var attributes = client.GetAttributes(remoteFile);
  4380. Assert.IsTrue(attributes.IsRegularFile);
  4381. Assert.AreEqual(0L, attributes.Size);
  4382. #endregion Verify if merely opening the file for create creates a zero-byte file
  4383. client.DeleteFile(remoteFile);
  4384. #region Verify if content is actually written to the file
  4385. var content = GenerateRandom(size: 100);
  4386. using (var s = client.Open(remoteFile, FileMode.Create))
  4387. {
  4388. Assert.IsTrue(s.CanRead);
  4389. Assert.IsTrue(s.CanWrite);
  4390. s.Write(content, offset: 0, content.Length);
  4391. }
  4392. using (var downloaded = new MemoryStream())
  4393. {
  4394. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4395. downloaded.Position = 0;
  4396. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4397. }
  4398. #endregion Verify if content is actually written to the file
  4399. }
  4400. finally
  4401. {
  4402. if (client.Exists(remoteFile))
  4403. {
  4404. client.DeleteFile(remoteFile);
  4405. }
  4406. }
  4407. }
  4408. }
  4409. [TestMethod]
  4410. public void Sftp_Open_PathAndMode_ModeIsCreate_ExistingFile()
  4411. {
  4412. const int fileSize = 5 * 1024;
  4413. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4414. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4415. using (var input = CreateMemoryStream(fileSize))
  4416. {
  4417. client.Connect();
  4418. var remoteFile = GenerateUniqueRemoteFileName();
  4419. if (client.Exists(remoteFile))
  4420. {
  4421. client.DeleteFile(remoteFile);
  4422. }
  4423. try
  4424. {
  4425. input.Position = 0;
  4426. client.UploadFile(input, remoteFile);
  4427. using (var stream = client.Open(remoteFile, FileMode.Create))
  4428. {
  4429. // Verify if merely opening the file for create overwrites the file
  4430. var attributes = client.GetAttributes(remoteFile);
  4431. Assert.IsTrue(attributes.IsRegularFile);
  4432. Assert.AreEqual(0L, attributes.Size);
  4433. stream.Write(newContent, offset: 0, newContent.Length);
  4434. stream.Position = 0;
  4435. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4436. }
  4437. }
  4438. finally
  4439. {
  4440. if (client.Exists(remoteFile))
  4441. {
  4442. client.DeleteFile(remoteFile);
  4443. }
  4444. }
  4445. }
  4446. }
  4447. [TestMethod]
  4448. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_FileDoesNotExist()
  4449. {
  4450. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4451. {
  4452. client.Connect();
  4453. var remoteFile = GenerateUniqueRemoteFileName();
  4454. if (client.Exists(remoteFile))
  4455. {
  4456. client.DeleteFile(remoteFile);
  4457. }
  4458. try
  4459. {
  4460. #region Verify if merely opening the file for create creates a zero-byte file
  4461. using (client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4462. {
  4463. }
  4464. Assert.IsTrue(client.Exists(remoteFile));
  4465. var attributes = client.GetAttributes(remoteFile);
  4466. Assert.IsTrue(attributes.IsRegularFile);
  4467. Assert.AreEqual(0L, attributes.Size);
  4468. #endregion Verify if merely opening the file for create creates a zero-byte file
  4469. client.DeleteFile(remoteFile);
  4470. #region Verify if content is actually written to the file
  4471. var content = GenerateRandom(size: 100);
  4472. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4473. {
  4474. s.Write(content, offset: 0, content.Length);
  4475. }
  4476. using (var downloaded = new MemoryStream())
  4477. {
  4478. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4479. downloaded.Position = 0;
  4480. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4481. }
  4482. #endregion Verify if content is actually written to the file
  4483. }
  4484. finally
  4485. {
  4486. if (client.Exists(remoteFile))
  4487. {
  4488. client.DeleteFile(remoteFile);
  4489. }
  4490. }
  4491. }
  4492. }
  4493. [TestMethod]
  4494. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_ExistingFile()
  4495. {
  4496. const int fileSize = 5 * 1024;
  4497. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4498. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4499. using (var input = CreateMemoryStream(fileSize))
  4500. {
  4501. client.Connect();
  4502. var remoteFile = GenerateUniqueRemoteFileName();
  4503. if (client.Exists(remoteFile))
  4504. {
  4505. client.DeleteFile(remoteFile);
  4506. }
  4507. try
  4508. {
  4509. input.Position = 0;
  4510. client.UploadFile(input, remoteFile);
  4511. using (var stream = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4512. {
  4513. // Verify if merely opening the file for create overwrites the file
  4514. var attributes = client.GetAttributes(remoteFile);
  4515. Assert.IsTrue(attributes.IsRegularFile);
  4516. Assert.AreEqual(0L, attributes.Size);
  4517. stream.Write(newContent, offset: 0, newContent.Length);
  4518. stream.Position = 0;
  4519. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4520. }
  4521. }
  4522. finally
  4523. {
  4524. if (client.Exists(remoteFile))
  4525. {
  4526. client.DeleteFile(remoteFile);
  4527. }
  4528. }
  4529. }
  4530. }
  4531. [TestMethod]
  4532. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_ExistingFile()
  4533. {
  4534. // use new content that contains less bytes than original content to
  4535. // verify whether file is first truncated
  4536. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4537. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4538. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4539. {
  4540. client.Connect();
  4541. var remoteFile = GenerateUniqueRemoteFileName();
  4542. if (client.Exists(remoteFile))
  4543. {
  4544. client.DeleteFile(remoteFile);
  4545. }
  4546. try
  4547. {
  4548. client.WriteAllBytes(remoteFile, originalContent);
  4549. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4550. {
  4551. s.Write(newContent, offset: 0, newContent.Length);
  4552. }
  4553. using (var downloaded = new MemoryStream())
  4554. {
  4555. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4556. downloaded.Position = 0;
  4557. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4558. }
  4559. }
  4560. finally
  4561. {
  4562. if (client.Exists(remoteFile))
  4563. {
  4564. client.DeleteFile(remoteFile);
  4565. }
  4566. }
  4567. }
  4568. }
  4569. [TestMethod]
  4570. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_FileDoesNotExist()
  4571. {
  4572. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4573. {
  4574. client.Connect();
  4575. var remoteFile = GenerateUniqueRemoteFileName();
  4576. if (client.Exists(remoteFile))
  4577. {
  4578. client.DeleteFile(remoteFile);
  4579. }
  4580. try
  4581. {
  4582. #region Verify if merely opening the file for create creates a zero-byte file
  4583. using (client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4584. {
  4585. }
  4586. Assert.IsTrue(client.Exists(remoteFile));
  4587. var attributes = client.GetAttributes(remoteFile);
  4588. Assert.IsTrue(attributes.IsRegularFile);
  4589. Assert.AreEqual(0L, attributes.Size);
  4590. #endregion Verify if merely opening the file for create creates a zero-byte file
  4591. client.DeleteFile(remoteFile);
  4592. #region Verify if content is actually written to the file
  4593. var content = GenerateRandom(size: 100);
  4594. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4595. {
  4596. s.Write(content, offset: 0, content.Length);
  4597. }
  4598. using (var downloaded = new MemoryStream())
  4599. {
  4600. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4601. downloaded.Position = 0;
  4602. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4603. }
  4604. #endregion Verify if content is actually written to the file
  4605. }
  4606. finally
  4607. {
  4608. if (client.Exists(remoteFile))
  4609. {
  4610. client.DeleteFile(remoteFile);
  4611. }
  4612. }
  4613. }
  4614. }
  4615. [TestMethod]
  4616. public void Sftp_Open_CreateNew_Write_ExistingFile()
  4617. {
  4618. const int fileSize = 5 * 1024;
  4619. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4620. using (var input = CreateMemoryStream(fileSize))
  4621. {
  4622. client.Connect();
  4623. var remoteFile = GenerateUniqueRemoteFileName();
  4624. if (client.Exists(remoteFile))
  4625. {
  4626. client.DeleteFile(remoteFile);
  4627. }
  4628. input.Position = 0;
  4629. try
  4630. {
  4631. client.UploadFile(input, remoteFile);
  4632. Stream stream = null;
  4633. try
  4634. {
  4635. stream = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write);
  4636. Assert.Fail();
  4637. }
  4638. catch (SshException)
  4639. {
  4640. }
  4641. finally
  4642. {
  4643. stream?.Dispose();
  4644. }
  4645. // Verify that the file was not modified
  4646. using (var downloaded = new MemoryStream())
  4647. {
  4648. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4649. input.Position = 0;
  4650. downloaded.Position = 0;
  4651. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4652. }
  4653. }
  4654. finally
  4655. {
  4656. if (client.Exists(remoteFile))
  4657. {
  4658. client.DeleteFile(remoteFile);
  4659. }
  4660. }
  4661. }
  4662. }
  4663. [TestMethod]
  4664. public void Sftp_Open_CreateNew_Write_FileDoesNotExist()
  4665. {
  4666. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4667. {
  4668. client.Connect();
  4669. var remoteFile = GenerateUniqueRemoteFileName();
  4670. if (client.Exists(remoteFile))
  4671. {
  4672. client.DeleteFile(remoteFile);
  4673. }
  4674. try
  4675. {
  4676. #region Verify if merely opening the file creates a zero-byte file
  4677. using (client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4678. {
  4679. }
  4680. Assert.IsTrue(client.Exists(remoteFile));
  4681. var attributes = client.GetAttributes(remoteFile);
  4682. Assert.IsTrue(attributes.IsRegularFile);
  4683. Assert.AreEqual(0L, attributes.Size);
  4684. #endregion Verify if merely opening the file creates it
  4685. client.DeleteFile(remoteFile);
  4686. #region Verify if content is actually written to the file
  4687. var content = GenerateRandom(size: 100);
  4688. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4689. {
  4690. s.Write(content, offset: 0, content.Length);
  4691. }
  4692. using (var downloaded = new MemoryStream())
  4693. {
  4694. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4695. downloaded.Position = 0;
  4696. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4697. }
  4698. #endregion Verify if content is actually written to the file
  4699. }
  4700. finally
  4701. {
  4702. if (client.Exists(remoteFile))
  4703. {
  4704. client.DeleteFile(remoteFile);
  4705. }
  4706. }
  4707. }
  4708. }
  4709. [TestMethod]
  4710. public void Sftp_Open_Open_Write_ExistingFile()
  4711. {
  4712. // use new content that contains less bytes than original content to
  4713. // verify whether file is first truncated
  4714. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4715. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4716. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4717. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4718. {
  4719. client.Connect();
  4720. var remoteFile = GenerateUniqueRemoteFileName();
  4721. if (client.Exists(remoteFile))
  4722. {
  4723. client.DeleteFile(remoteFile);
  4724. }
  4725. try
  4726. {
  4727. client.WriteAllBytes(remoteFile, originalContent);
  4728. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  4729. {
  4730. s.Write(newContent, offset: 0, newContent.Length);
  4731. }
  4732. using (var downloaded = new MemoryStream())
  4733. {
  4734. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4735. downloaded.Position = 0;
  4736. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4737. }
  4738. }
  4739. finally
  4740. {
  4741. if (client.Exists(remoteFile))
  4742. {
  4743. client.DeleteFile(remoteFile);
  4744. }
  4745. }
  4746. }
  4747. }
  4748. [TestMethod]
  4749. public void Sftp_Open_Open_Write_FileDoesNotExist()
  4750. {
  4751. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4752. {
  4753. client.Connect();
  4754. var remoteFile = GenerateUniqueRemoteFileName();
  4755. if (client.Exists(remoteFile))
  4756. {
  4757. client.DeleteFile(remoteFile);
  4758. }
  4759. try
  4760. {
  4761. Stream stream = null;
  4762. try
  4763. {
  4764. stream = client.Open(remoteFile, FileMode.Open, FileAccess.Write);
  4765. Assert.Fail();
  4766. }
  4767. catch (SshException)
  4768. {
  4769. }
  4770. finally
  4771. {
  4772. stream?.Dispose();
  4773. }
  4774. Assert.IsFalse(client.Exists(remoteFile));
  4775. }
  4776. finally
  4777. {
  4778. if (client.Exists(remoteFile))
  4779. {
  4780. client.DeleteFile(remoteFile);
  4781. }
  4782. }
  4783. }
  4784. }
  4785. [TestMethod]
  4786. public void Sftp_Open_OpenOrCreate_Write_ExistingFile()
  4787. {
  4788. // use new content that contains less bytes than original content to
  4789. // verify whether file is first truncated
  4790. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4791. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4792. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4793. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4794. {
  4795. client.Connect();
  4796. var remoteFile = GenerateUniqueRemoteFileName();
  4797. if (client.Exists(remoteFile))
  4798. {
  4799. client.DeleteFile(remoteFile);
  4800. }
  4801. try
  4802. {
  4803. client.WriteAllBytes(remoteFile, originalContent);
  4804. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4805. {
  4806. s.Write(newContent, offset: 0, newContent.Length);
  4807. }
  4808. using (var downloaded = new MemoryStream())
  4809. {
  4810. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4811. downloaded.Position = 0;
  4812. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4813. }
  4814. }
  4815. finally
  4816. {
  4817. if (client.Exists(remoteFile))
  4818. {
  4819. client.DeleteFile(remoteFile);
  4820. }
  4821. }
  4822. }
  4823. }
  4824. [TestMethod]
  4825. public void Sftp_Open_OpenOrCreate_Write_FileDoesNotExist()
  4826. {
  4827. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4828. {
  4829. client.Connect();
  4830. var remoteFile = GenerateUniqueRemoteFileName();
  4831. if (client.Exists(remoteFile))
  4832. {
  4833. client.DeleteFile(remoteFile);
  4834. }
  4835. try
  4836. {
  4837. #region Verify if merely opening the file creates a zero-byte file
  4838. using (client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4839. {
  4840. }
  4841. Assert.IsTrue(client.Exists(remoteFile));
  4842. var attributes = client.GetAttributes(remoteFile);
  4843. Assert.IsTrue(attributes.IsRegularFile);
  4844. Assert.AreEqual(0L, attributes.Size);
  4845. #endregion Verify if merely opening the file creates it
  4846. client.DeleteFile(remoteFile);
  4847. #region Verify if content is actually written to the file
  4848. var content = GenerateRandom(size: 100);
  4849. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4850. {
  4851. s.Write(content, offset: 0, content.Length);
  4852. }
  4853. using (var downloaded = new MemoryStream())
  4854. {
  4855. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4856. downloaded.Position = 0;
  4857. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4858. }
  4859. #endregion Verify if content is actually written to the file
  4860. }
  4861. finally
  4862. {
  4863. if (client.Exists(remoteFile))
  4864. {
  4865. client.DeleteFile(remoteFile);
  4866. }
  4867. }
  4868. }
  4869. }
  4870. [TestMethod]
  4871. public void Sftp_Open_Truncate_Write_ExistingFile()
  4872. {
  4873. const int fileSize = 5 * 1024;
  4874. // use new content that contains less bytes than original content to
  4875. // verify whether file is first truncated
  4876. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4877. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4878. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4879. using (var input = CreateMemoryStream(fileSize))
  4880. {
  4881. client.Connect();
  4882. var remoteFile = GenerateUniqueRemoteFileName();
  4883. if (client.Exists(remoteFile))
  4884. {
  4885. client.DeleteFile(remoteFile);
  4886. }
  4887. input.Position = 0;
  4888. try
  4889. {
  4890. client.WriteAllBytes(remoteFile, originalContent);
  4891. using (var s = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write))
  4892. {
  4893. s.Write(newContent, offset: 0, newContent.Length);
  4894. }
  4895. using (var downloaded = new MemoryStream())
  4896. {
  4897. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4898. input.Position = 0;
  4899. downloaded.Position = 0;
  4900. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4901. }
  4902. }
  4903. finally
  4904. {
  4905. if (client.Exists(remoteFile))
  4906. {
  4907. client.DeleteFile(remoteFile);
  4908. }
  4909. }
  4910. }
  4911. }
  4912. [TestMethod]
  4913. public void Sftp_Open_Truncate_Write_FileDoesNotExist()
  4914. {
  4915. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4916. {
  4917. client.Connect();
  4918. var remoteFile = GenerateUniqueRemoteFileName();
  4919. if (client.Exists(remoteFile))
  4920. {
  4921. client.DeleteFile(remoteFile);
  4922. }
  4923. try
  4924. {
  4925. Stream stream = null;
  4926. try
  4927. {
  4928. stream = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write);
  4929. Assert.Fail();
  4930. }
  4931. catch (SshException)
  4932. {
  4933. }
  4934. Assert.IsFalse(client.Exists(remoteFile));
  4935. }
  4936. finally
  4937. {
  4938. if (client.Exists(remoteFile))
  4939. {
  4940. client.DeleteFile(remoteFile);
  4941. }
  4942. }
  4943. }
  4944. }
  4945. [TestMethod]
  4946. public void Sftp_SetLastAccessTime()
  4947. {
  4948. var testFilePath = "/home/sshnet/test-file.txt";
  4949. var testContent = "File";
  4950. using var client = new SftpClient(_connectionInfoFactory.Create());
  4951. client.Connect();
  4952. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  4953. client.UploadFile(fileStream, testFilePath);
  4954. try
  4955. {
  4956. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  4957. client.SetLastAccessTime(testFilePath, newTime);
  4958. var time = client.GetLastAccessTime(testFilePath);
  4959. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  4960. }
  4961. finally
  4962. {
  4963. client.DeleteFile(testFilePath);
  4964. }
  4965. }
  4966. [TestMethod]
  4967. public void Sftp_SetLastAccessTimeUtc()
  4968. {
  4969. var testFilePath = "/home/sshnet/test-file.txt";
  4970. var testContent = "File";
  4971. using var client = new SftpClient(_connectionInfoFactory.Create());
  4972. client.Connect();
  4973. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  4974. client.UploadFile(fileStream, testFilePath);
  4975. try
  4976. {
  4977. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  4978. client.SetLastAccessTimeUtc(testFilePath, newTime);
  4979. var time = client.GetLastAccessTimeUtc(testFilePath);
  4980. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  4981. }
  4982. finally
  4983. {
  4984. client.DeleteFile(testFilePath);
  4985. }
  4986. }
  4987. [TestMethod]
  4988. public void Sftp_SetLastWriteTime()
  4989. {
  4990. var testFilePath = "/home/sshnet/test-file.txt";
  4991. var testContent = "File";
  4992. using var client = new SftpClient(_connectionInfoFactory.Create());
  4993. client.Connect();
  4994. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  4995. client.UploadFile(fileStream, testFilePath);
  4996. try
  4997. {
  4998. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  4999. client.SetLastWriteTime(testFilePath, newTime);
  5000. var time = client.GetLastWriteTime(testFilePath);
  5001. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5002. }
  5003. finally
  5004. {
  5005. client.DeleteFile(testFilePath);
  5006. }
  5007. }
  5008. [TestMethod]
  5009. public void Sftp_SetLastWriteTimeUtc()
  5010. {
  5011. var testFilePath = "/home/sshnet/test-file.txt";
  5012. var testContent = "File";
  5013. using var client = new SftpClient(_connectionInfoFactory.Create());
  5014. client.Connect();
  5015. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5016. client.UploadFile(fileStream, testFilePath);
  5017. try
  5018. {
  5019. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5020. client.SetLastWriteTimeUtc(testFilePath, newTime);
  5021. var time = client.GetLastWriteTimeUtc(testFilePath);
  5022. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5023. }
  5024. finally
  5025. {
  5026. client.DeleteFile(testFilePath);
  5027. }
  5028. }
  5029. [TestMethod]
  5030. public void Sftp_SftpFileStream_Fuzz()
  5031. {
  5032. const int OperationCount = 100;
  5033. const int MaxBufferSize = 1000;
  5034. const int MaxFileSize = 15_000;
  5035. int seed = Environment.TickCount;
  5036. Console.WriteLine("Using seed " + seed);
  5037. var random = new Random(seed);
  5038. using var client = new SftpClient(_connectionInfoFactory.Create())
  5039. {
  5040. BufferSize = 100
  5041. };
  5042. client.Connect();
  5043. // We will perform operations on an SftpFileStream and a local
  5044. // System.IO.FileStream, and check that the results are the same.
  5045. // This could use a MemoryStream for the local side, except for the
  5046. // fact that performing a 0-byte write at a position beyond the length
  5047. // of the MemoryStream causes its length to increase, which is not the
  5048. // case for FileStream. Since we've got 'FileStream' in the name, we
  5049. // check that we align with FileStream's behaviour.
  5050. string remoteFilePath = GenerateUniqueRemoteFileName();
  5051. string localFilePath = Path.GetTempFileName();
  5052. byte[] fileBytes = new byte[1024];
  5053. random.NextBytes(fileBytes);
  5054. File.WriteAllBytes(localFilePath, fileBytes);
  5055. client.WriteAllBytes(remoteFilePath, fileBytes);
  5056. try
  5057. {
  5058. using (var local = File.Open(localFilePath, FileMode.Open, FileAccess.ReadWrite))
  5059. using (var remote = client.Open(remoteFilePath, FileMode.Open, FileAccess.ReadWrite))
  5060. {
  5061. for (int i = 0; i < OperationCount; i++)
  5062. {
  5063. #pragma warning disable IDE0010 // Add missing cases
  5064. int op = random.Next(5);
  5065. switch (op)
  5066. {
  5067. case 0 when local.Length < MaxFileSize: // Write
  5068. {
  5069. var buffer = new byte[random.Next(0, MaxBufferSize)];
  5070. random.NextBytes(buffer);
  5071. int offset = random.Next(0, buffer.Length + 1);
  5072. int count = random.Next(0, buffer.Length - offset + 1);
  5073. remote.Write(buffer, offset, count);
  5074. local.Write(buffer, offset, count);
  5075. break;
  5076. }
  5077. case 1: // Read
  5078. {
  5079. var remoteBuffer = new byte[random.Next(0, MaxBufferSize)];
  5080. var localBuffer = new byte[remoteBuffer.Length];
  5081. int offset = random.Next(0, remoteBuffer.Length + 1);
  5082. int count = random.Next(0, remoteBuffer.Length - offset + 1);
  5083. int remoteRead = ReadExactly(remote, remoteBuffer, offset, count);
  5084. int localRead = ReadExactly(local, localBuffer, offset, count);
  5085. Assert.AreEqual(localRead, remoteRead);
  5086. CollectionAssert.AreEqual(localBuffer, remoteBuffer);
  5087. break;
  5088. }
  5089. case 2 when local.Length < MaxFileSize: // Seek
  5090. {
  5091. int position = (int)local.Position;
  5092. int length = (int)local.Length;
  5093. SeekOrigin origin = (SeekOrigin)random.Next(0, 3);
  5094. long offset = 0;
  5095. switch (origin)
  5096. {
  5097. case SeekOrigin.Begin:
  5098. offset = random.Next(0, length * 2);
  5099. break;
  5100. case SeekOrigin.Current:
  5101. offset = random.Next(-position, position);
  5102. break;
  5103. case SeekOrigin.End:
  5104. offset = random.Next(-length, length);
  5105. break;
  5106. }
  5107. long newPosRemote = remote.Seek(offset, origin);
  5108. long newPosLocal = local.Seek(offset, origin);
  5109. Assert.AreEqual(newPosLocal, newPosRemote);
  5110. Assert.AreEqual(local.Length, remote.Length);
  5111. break;
  5112. }
  5113. case 3: // SetLength
  5114. {
  5115. long newLength = random.Next(0, MaxFileSize);
  5116. remote.SetLength(newLength);
  5117. local.SetLength(newLength);
  5118. Assert.AreEqual(local.Length, remote.Length);
  5119. Assert.AreEqual(local.Position, remote.Position);
  5120. break;
  5121. }
  5122. case 4: // Flush
  5123. {
  5124. remote.Flush();
  5125. local.Flush();
  5126. break;
  5127. }
  5128. }
  5129. #pragma warning restore IDE0010 // Add missing cases
  5130. }
  5131. }
  5132. CollectionAssert.AreEqual(File.ReadAllBytes(localFilePath), client.ReadAllBytes(remoteFilePath));
  5133. }
  5134. finally
  5135. {
  5136. File.Delete(localFilePath);
  5137. if (client.Exists(remoteFilePath))
  5138. {
  5139. client.DeleteFile(remoteFilePath);
  5140. }
  5141. }
  5142. }
  5143. private static IEnumerable<object[]> GetSftpUploadFileFileStreamData()
  5144. {
  5145. yield return new object[] { 0 };
  5146. yield return new object[] { 5 * 1024 * 1024 };
  5147. }
  5148. private static Encoding GetRandomEncoding()
  5149. {
  5150. var random = new Random().Next(1, 4);
  5151. switch (random)
  5152. {
  5153. case 1:
  5154. return Encoding.Unicode;
  5155. case 2:
  5156. return Encoding.UTF8;
  5157. default:
  5158. Debug.Assert(random == 3);
  5159. return Encoding.UTF32;
  5160. }
  5161. }
  5162. private void DownloadFileRandomMethod(SftpClient client, string path, Stream output)
  5163. {
  5164. Console.Write($"Downloading '{path}'");
  5165. var random = new Random().Next(1, 7);
  5166. switch (random)
  5167. {
  5168. case 1:
  5169. Console.WriteLine($" with {nameof(SftpClient.DownloadFile)}");
  5170. client.DownloadFile(path, output);
  5171. break;
  5172. case 2:
  5173. Console.WriteLine($" with {nameof(SftpClient.DownloadFileAsync)}");
  5174. client.DownloadFileAsync(path, output).GetAwaiter().GetResult();
  5175. break;
  5176. case 3:
  5177. Console.WriteLine($" with {nameof(SftpClient.BeginDownloadFile)}");
  5178. client.EndDownloadFile(client.BeginDownloadFile(path, output));
  5179. break;
  5180. case 4:
  5181. Console.WriteLine($" with {nameof(SftpFileStream.CopyTo)}");
  5182. using (var fs = client.OpenRead(path))
  5183. {
  5184. fs.CopyTo(output);
  5185. }
  5186. break;
  5187. case 5:
  5188. Console.WriteLine($" with {nameof(SftpFileStream.CopyToAsync)}");
  5189. using (var fs = client.OpenAsync(path, FileMode.Open, FileAccess.Read, CancellationToken.None).GetAwaiter().GetResult())
  5190. {
  5191. fs.CopyToAsync(output).GetAwaiter().GetResult();
  5192. }
  5193. break;
  5194. default:
  5195. Debug.Assert(random == 6);
  5196. Console.WriteLine($" with {nameof(SftpClient.ReadAllBytes)}");
  5197. byte[] bytes = client.ReadAllBytes(path);
  5198. output.Write(bytes, 0, bytes.Length);
  5199. break;
  5200. }
  5201. }
  5202. private static byte[] GetBytesWithPreamble(string text, Encoding encoding)
  5203. {
  5204. var preamble = encoding.GetPreamble();
  5205. var textBytes = encoding.GetBytes(text);
  5206. if (preamble.Length != 0)
  5207. {
  5208. var textAndPreambleBytes = new byte[preamble.Length + textBytes.Length];
  5209. Buffer.BlockCopy(preamble, srcOffset: 0, textAndPreambleBytes, dstOffset: 0, preamble.Length);
  5210. Buffer.BlockCopy(textBytes, srcOffset: 0, textAndPreambleBytes, preamble.Length, textBytes.Length);
  5211. return textAndPreambleBytes;
  5212. }
  5213. return textBytes;
  5214. }
  5215. private static decimal CalculateTransferSpeed(long length, long elapsedMilliseconds)
  5216. {
  5217. return (length / 1024m) / (elapsedMilliseconds / 1000m);
  5218. }
  5219. /// <summary>
  5220. /// Similar to the netcore ReadExactly but without throwing on end of stream.
  5221. /// </summary>
  5222. private static int ReadExactly(Stream stream, byte[] buffer, int offset, int count)
  5223. {
  5224. int totalRead = 0;
  5225. while (totalRead < count)
  5226. {
  5227. int read = stream.Read(buffer, offset + totalRead, count - totalRead);
  5228. if (read == 0)
  5229. {
  5230. return totalRead;
  5231. }
  5232. totalRead += read;
  5233. }
  5234. return totalRead;
  5235. }
  5236. private static byte[] GenerateRandom(int size)
  5237. {
  5238. var random = new Random();
  5239. var randomContent = new byte[size];
  5240. random.NextBytes(randomContent);
  5241. return randomContent;
  5242. }
  5243. private static Stream CreateStreamWithContent(string content)
  5244. {
  5245. var memoryStream = new MemoryStream();
  5246. var sw = new StreamWriter(memoryStream, Encoding.ASCII, 1024);
  5247. sw.Write(content);
  5248. sw.Flush();
  5249. memoryStream.Position = 0;
  5250. return memoryStream;
  5251. }
  5252. private static string GenerateUniqueRemoteFileName()
  5253. {
  5254. return $"/home/sshnet/{Guid.NewGuid():D}";
  5255. }
  5256. }
  5257. }